Creating REST APIs with Express
When building a web application, it is common to provide a set of APIs that allow the frontend to communicate with the backend. REST (Representational State Transfer) is a popular architectural style used for designing networked applications, and Express.js is a popular framework for building RESTful APIs with Node.js.
To create REST APIs with Express, follow these steps:
- Set up the Express application
1const express = require('express');
2const app = express();
- Define routes
Routes define the different endpoints of your API and the logic to handle each endpoint. For example:
1app.get('/api/users', (req, res) => {
2 // Logic to retrieve users
3 const users = [
4 { id: 1, name: 'John' },
5 { id: 2, name: 'Jane' },
6 ];
7
8 // Send the users in the response
9 res.json(users);
10});
11
12app.post('/api/users', (req, res) => {
13 // Logic to create a new user
14 const newUser = { id: 3, name: 'Sam' };
15
16 // Send the new user in the response
17 res.json(newUser);
18});
- Start the server
1app.listen(3000, () => {
2 console.log('Server started on port 3000');
3});
These steps will set up a basic Express application with two routes: /api/users
for retrieving users and /api/users
for creating a new user. You can customize the routes and logic based on the requirements of your API.
By following these steps, you can create powerful REST APIs using Express and Node.js.
xxxxxxxxxx
*/
/* To create a REST API with Express, we'll need to follow a few steps:
1. Set up the Express application
const express = require('express');
const app = express();
2. Define routes
// GET request to /api/users
app.get('/api/users', (req, res) => {
// Logic to retrieve users
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
];
// Send the users in the response
res.json(users);
});
// POST request to /api/users
app.post('/api/users', (req, res) => {
// Logic to create a new user
const newUser = { id: 3, name: 'Sam' };
// Send the new user in the response
res.json(newUser);
});