Mark As Completed Discussion

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:

  1. Set up the Express application
JAVASCRIPT
1const express = require('express');
2const app = express();
  1. Define routes

Routes define the different endpoints of your API and the logic to handle each endpoint. For example:

JAVASCRIPT
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});
  1. Start the server
JAVASCRIPT
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.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment