Node.js Express REST API Documentation

1. Introduction

Welcome to the documentation for Node.js Express REST API. This section provides an overview of the API and its functionality.

2. Setting Up Express

To get started, you need to set up an Express application. Follow the steps below to initialize your project and install the necessary dependencies.

const express = require('express');
const app = express();

// Define your routes and middleware here

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

4. Handling HTTP Methods

4.1 GET Method

The GET method is used to retrieve data from the server. Below is an example of handling a GET request to retrieve todos.

app.get('/api/todos', (req, res) => {
  // Your logic to retrieve todos from the database
  res.json({ todos: [...] });
});

4.2 POST Method

The POST method is used to submit data to the server to create a new resource. Below is an example of handling a POST request to create a new user.

app.post('/api/users', (req, res) => {
  // Logic to create a new user based on request body
  res.status(201).json({ message: 'User created successfully' });
});

4.3 DELETE Method

The DELETE method is used to delete a resource identified by a specific URI. Below is an example of handling a DELETE request to delete a user by ID.

app.delete('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  // Logic to delete user by ID
  res.json({ message: 'User deleted successfully' });
});

4.4 PUT vs PATCH

Both PUT and PATCH methods are used to update resources, but they differ in their behavior. PUT is used to update the entire resource, while PATCH is used to apply partial modifications to the resource.

Here's an example illustrating the difference between PUT and PATCH:

app.put('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  // Logic to update user by ID with entire resource
  res.json({ message: 'User updated successfully' });
});

app.patch('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  // Logic to update user by ID with partial modifications
  res.json({ message: 'User updated successfully' });
});

5. Handling Request Parameters

Learn how to handle request parameters, both from the URL and request body. Here's an example of handling a parameter in the URL.

app.get('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  // Your logic to retrieve user details by ID
  res.json({ user: { id: userId, name: 'John Doe' } });
});
Back

Package.json

Arrow