Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Implementing CRUD Endpoints | Building RESTful APIs
Express.js Essentials for Backend Development

Implementing CRUD Endpoints

Glissez pour afficher le menu

Implementing CRUD Endpoints

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations most APIs perform when working with data.

In Express.js, each CRUD operation is usually connected to a specific HTTP method.

Basic CRUD Example

The following example uses a simple in-memory array instead of a database. This keeps the focus on how Express.js endpoints work.

const express = require('express');

const app = express();

app.use(express.json());

let users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

app.get('/users', (req, res) => {
  res.json(users);
});

app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };

  users.push(newUser);

  res.status(201).json(newUser);
});

app.put('/users/:id', (req, res) => {
  const user = users.find(user => user.id === Number(req.params.id));

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  user.name = req.body.name;

  res.json(user);
});

app.delete('/users/:id', (req, res) => {
  users = users.filter(user => user.id !== Number(req.params.id));

  res.json({ message: 'User deleted' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

How It Works

  • The GET /users endpoint returns all users;
  • The POST /users endpoint reads data from req.body, creates a new user, and returns it with the 201 status code;
  • The PUT /users/:id endpoint uses req.params.id to find a user and update the user's name;
  • The DELETE /users/:id endpoint removes a user from the array and returns a confirmation message;
  • The express.json() middleware is important because it allows Express.js to read JSON data from the request body.
Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 2

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 4. Chapitre 2
some-alt