How to Use HTTP Methods in Express.js for REST APIs

How to Use HTTP Methods in Express.js for REST APIs

In this blog post, you will learn about REST APIs and how to create them using Express.js, a popular web framework for Node.js. REST stands for Representational State Transfer, and it defines a set of rules for client-server communication over HTTP. One of the key concepts of REST is using HTTP methods (also known as verbs) to perform actions on a resource.

What are HTTP methods?

HTTP methods are request types that indicate the desired interaction between the client and the server. There are many HTTP methods, but the most common ones are:

  • GET: This method is used to retrieve data from the server without making any changes. For example, you can use GET to fetch a list of users from a database.
  • POST: This method is used to create new data on the server. For example, you can use POST to add a new user to a database.
  • PUT: This method is used to update existing data on the server. For example, you can use PUT to modify the details of an existing user in a database.
  • DELETE: This method is used to delete data from the server. For example, you can use DELETE to remove a user from a database.
  • PATCH: This method is used to partially update data on the server. For example, you can use PATCH to change only the name of an existing user in a database.

How to use HTTP methods in Express.js?

Express.js is a web framework for Node.js that simplifies server creation, route handling, middleware integration, and error management. You can also enhance its functionality using various libraries and plugins.

To implement HTTP methods in Express.js, you need to define routes that specify the path and the callback function for each request. The callback function takes two parameters: req (request) and res (response). You can access various properties and methods of these objects, such as req.params, req.body, res.render, res.send, etc.

You also need to use a middleware (such as body-parser) that parses the request body and makes it available as req.body. This is useful for POST, PUT, and PATCH requests that send data along with the request.

Here are some examples of how to use HTTP methods in Express.js for a simple web application that manages users:

GET

To handle GET requests, you can use app.get(path, callback) in Express.js. For example, if you want to fetch a list of users from a database, you can define a route like this:

// Require Express.js
const express = require('express');
// Create an app instance
const app = express();
// Require user model
const UserModel = require('./models/userModel');

// Define a route for GET /users
app.get('/users', (req, res) => {
  // Fetch all users from the database
  UserModel.getAll((err, users) => {
    if (err) {
      // Handle error
      res.status(500).send('Server error');
    } else {
      // Render user list view with users data
      res.render('userList', { users });
    }
  });
});

POST

To handle POST requests, you can use app.post(path, callback) in Express.js. For example, if you want to create a new user in a database, you can define a route like this:

// Require Express.js
const express = require('express');
// Create an app instance
const app = express();
// Require body-parser middleware
const bodyParser = require('body-parser');
// Require user model
const UserModel = require('./models/userModel');

// Use body-parser middleware to parse request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define a route for POST /users
app.post('/users', (req, res) => {
  // Get user data from request body
  const userData = req.body;
  // Create a new user in the database
  UserModel.create(userData, (err, user) => {
    if (err) {
      // Handle error
      res.status(500).send('Server error');
    } else {
      // Redirect to user profile view with user data
      res.redirect(`/users/${user.id}`);
    }
  });
});

PUT

To handle PUT requests, you can use app.put(path, callback) in Express.js. For example, if you want to update an existing user in a database, you can define a route like this:

// Require Express.js
const express = require('express');
// Create an app instance
const app = express();
// Require body-parser middleware
const bodyParser = require('body-parser');
// Require user model
const UserModel = require('./models/userModel');

// Use body-parser middleware to parse request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define a route for PUT /users/:id
app.put('/users/:id', (req, res) => {
  // Get user id from request params
  const userId = req.params.id;
  // Get new user data from request body
  const newUserData = req.body;
  // Update the user in the database
  UserModel.update(userId, newUserData, (err, user) => {
    if (err) {
      // Handle error
      res.status(500).send('Server error');
    } else {
      // Redirect to user profile view with updated user data
      res.redirect(`/users/${user.id}`);
    }
  });
});

DELETE

To handle DELETE requests, you can use app.delete(path, callback) in Express.js. For example, if you want to delete a user from a database, you can define a route like this:

// Require Express.js
const express = require('express');
// Create an app instance
const app = express();
// Require user model
const UserModel = require('./models/userModel');

// Define a route for DELETE /users/:id
app.delete('/users/:id', (req, res) => {
  // Get user id from request params
  const userId = req.params.id;
  // Delete the user from the database
  UserModel.delete(userId, (err, user) => {
    if (err) {
      // Handle error
      res.status(500).send('Server error');
    } else {
      // Redirect to user list view
      res.redirect('/users');
    }
  });
});

PATCH

To handle PATCH requests, you can use app.patch(path, callback) in Express.js. For example, if you want to partially update a user in a database, you can define a route like this:

// Require Express.js
const express = require('express');
// Create an app instance
const app = express();
// Require body-parser middleware
const bodyParser = require('body-parser');
// Require user model
const UserModel = require('./models/userModel');

// Use body-parser middleware to parse request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define a route for PATCH /users/:id
app.patch('/users/:id', (req, res) => {
  // Get user id from request params
  const userId = req.params.id;
  // Get updated user data from request body
  const updatedUserData = req.body;
  // Partially update the user in the database
  UserModel.patch(userId, updatedUserData, (err, user) => {
    if (err) {
      // Handle error
      res.status(500).send('Server error');
    } else {
      // Redirect to user profile view with updated user data
      res.redirect(`/users/${user.id}`);
    }
  });
});

So, this was all about methods on should know while making REST APIs

I hope you found this post useful and informative. If you have any questions or any feedback, feel free to leave a comment below. Happy coding!

Here are my socials

Did you find this article valuable?

Support Mayank Singh by becoming a sponsor. Any amount is appreciated!