Created
July 13, 2023 16:28
-
-
Save gourab337/5bf7454e76037020eb50d9e773bf6f20 to your computer and use it in GitHub Desktop.
RESTful APIs using NodeJS and Express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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