Building a RESTful API with Express.js: A Beginner’s Guide

In this tutorial, we will walk through the process of building a RESTful API using Express.js, a popular Node.js web framework. We will cover the basics of RESTful API design, including HTTP methods, as well as how to handle requests and responses using Express.js. By the end of this tutorial, you will have a basic understanding of how to build a simple RESTful API with Express.js.

Shahzaib Khan
4 min readMar 3, 2023

Introduction

A RESTful API (Representational State Transfer API) is a type of web API that uses HTTP requests to interact with web resources. It is based on the principles of REST, a software architectural style that defines a set of constraints for creating scalable, distributed systems.

A RESTful API typically exposes resources as URLs, and supports a set of operations (called CRUD operations) for interacting with those resources:

  • Create (POST): Create a new resource.
  • Read (GET): Retrieve an existing resource.
  • Update (PUT/PATCH): Update an existing resource.
  • Delete (DELETE): Remove an existing resource.

Now, let’s move on to building a RESTful API with Express.js.

Building a RESTful API with Express.js

Express.js is a popular web framework for building Node.js applications, and it provides a simple, yet powerful way to build RESTful APIs.

To build a RESTful API with Express.js, we need to follow these steps:

  1. Install and set up Express.js: You can install Express.js using npm, and then set up a basic Express.js server.
  2. Define routes: Use the Express.js Router to define routes for your API, specifying the HTTP method (GET, POST, PUT, DELETE), the route URL, and the callback function that handles the request.
  3. Implement CRUD operations: Implement the CRUD operations for each route using a database or data storage mechanism. For example, you can use MongoDB with the Mongoose ORM to store and retrieve data.
  4. Test the API: Use a tool like Postman to test your API, sending requests to each route and verifying that the correct response is returned.

Install and set up Express.js:

First, we need to install Express.js using npm. Create a new directory for our project and run the following command in the terminal:

npm install express --save

Next, create a new file called app.js in the root directory of our project and add the following code:

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

const port = 3000;

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

Define routes and Implement CRUD operations:

We will use the Express.js Router to define routes for our API. Let’s create a new file called routes.js and add the following code:

const express = require('express');
const router = express.Router();

// Define routes
router.get('/users', (req, res) => {
res.send('List of users');
});

router.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Details of user ${userId}`);
});

router.post('/users', (req, res) => {
res.send('Create a new user');
});

router.put('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Update user ${userId}`);
});

router.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Delete user ${userId}`);
});

module.exports = router;

Mount the routes: In app.js, we need to mount the routes by requiring the routes.js file and using the app.use() method to mount the router to a specific path. Update app.js to the following:

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

const routes = require('./routes');

app.use('/api', routes);

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

Test the API:

Use a tool like Postman to test the API by sending requests to each route and verifying that the correct response is returned. For example, send a GET request to http://localhost:3000/api/users and expect to see the response 'List of users'.

Conclusion

That’s it! This is a basic example of building a RESTful API with Express.js. From here, we can continue to expand our API by adding more routes and implementing CRUD operations with a database or data storage mechanism. To learn more, you can use the following links:

Did i missed anything, if so leave it as a comment :)

Also, If you are looking for professional services to help you learn about these powerful tool and improve your development process, please feel free to connect @ https://www.linkedin.com/in/shahzaibkhan/

If you enjoyed this post…it would mean a lot to me if you could click on the “claps” icon…up to 50 claps allowed — Thank You!

--

--

Shahzaib Khan

Developer / Data Scientist / Computer Science Enthusiast. Founder @ Interns.pk You can connect with me @ https://linkedin.com/in/shahzaibkhan/