For detailed description:
https://expressjs.com/en/starter/installing.html
Create packge.json
npm init
Create Entry Point file server.js
Create HTTP Server in server.js
→ Use express
npm install express
Create requests.http
and write the server requests there and click on send request
get <http://localhost:4000/users>
Add API Routing
Syntax: app.METHOD ( path , request handler )
app
: This is an instance of an Express applicationMETHOD
: This represents an HTTP method → get
, post
, put
, delete
path
: This is the endpoint of the APIrequestHandler
: This is a function that gets executed when the route is matched. It typically takes two arguments, req
(the request object) and res
(the response object) (req, res) => {}
app.get('/users', (req, res) => {
res.send({message: 'All Users'});
});
Parametrized Request
/users/:id
, where :id
is a dynamic parameter representing the user ID.// Send 1 user by id
app.get('/users/:id', (req, res) => {
const userId = Number(req.params.id);
// Search user by id in usersList array
let userById = usersList.find(user=>user.id==userId);
if(userById === undefined){
res.send({message: 'User not found'});
}
else{
res.send({message: 'User by Id', payload: userById});
}
});
For initial learning stages , we use a pseudo Client side application called REST Client.
Postman can also be used for testing the REST API.
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=humao.rest-client
requests.http
in folder of server.