Skip to content

Instantly share code, notes, and snippets.

@gourab337
Created July 13, 2023 16:28
Show Gist options
  • Save gourab337/5bf7454e76037020eb50d9e773bf6f20 to your computer and use it in GitHub Desktop.
Save gourab337/5bf7454e76037020eb50d9e773bf6f20 to your computer and use it in GitHub Desktop.
RESTful APIs using NodeJS and Express
const express = require('express');
const app = express();
const PORT = 3232;
// GET endpoint
app.get('/tshirt', (req, res) => {
res.status(200).send({
tshirt: '👕',
size: 'large'
})
});
// Middleware to parse JSON body
app.use( express.json() )
// POST endpoint
app.post('/tshirt/:id', (req, res) => {
const { id } = req.params;
const { logo } = req.body;
if (!logo) {
res.status(418).send({ message: 'We need a logo!' })
}
res.send({
tshirt: `👕 with your ${logo}`,
});
});
// Start the server
app.listen(
PORT,
() => console.log(`it's live on localhost:${PORT}`)
)
1. npm init -y
2. npm install express
3. Create a javascript file named index.js and copy the contents of gist.
4. Execute `node .` in the terminal after saving the files.
5. Test using postman.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment