DEV Community

Cover image for Express.js Crash Course: Build a RESTful API with Middleware
Ghazi Khan
Ghazi Khan

Posted on • Originally published at ghazikhan.in

Express.js Crash Course: Build a RESTful API with Middleware

Introduction

If you're diving into the world of backend development, learning how to build APIs is an essential skill. One of the most popular frameworks for Node.js developers is Express.js—a fast, minimalist web framework that helps you create robust APIs with ease. In this blog post, we'll break down the concepts from my recent Express.js Crash Course, where you’ll learn to build a RESTful API in just under 30 minutes!

Here’s a step-by-step walkthrough of the key topics covered in the video. If you want to code along, check out the full video on YouTube: Express.js Crash Course.

What is Express.js?

Express.js is a lightweight framework for Node.js that allows you to create powerful web applications and APIs with minimal setup. It abstracts away some of the repetitive tasks like routing, handling requests and responses, and serving static files, making it easier to focus on your application’s logic.

Express is unopinionated, which means it doesn’t enforce any specific project structure or design patterns, giving you flexibility in how you build your application. It's highly extensible through middleware, which is key to unlocking more advanced features.

Video Tutorial if you don't like to read complete blog

Step 1: Setting Up Your Express Project

To get started, make sure you have Node.js installed on your system. You can create a new Express project by initializing a Node.js application and installing Express.js via npm.

mkdir express-crash-course
cd express-crash-course
npm init -y
npm install express
Enter fullscreen mode Exit fullscreen mode

After setting up your project, create a file called index.js. This will be the entry point of your Express application.

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

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

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Now run the server:

node index.js
Enter fullscreen mode Exit fullscreen mode

Your first Express server is now up and running! Visit http://localhost:3000 in your browser, and you'll see the message "Hello World!"

Step 2: Middleware – The Heart of Express.js

One of the key features of Express.js is middleware. Middleware functions have access to the request (req), response (res), and the next() function, which allows the request to move on to the next middleware in the stack.

You can use middleware for tasks like logging, authentication, and modifying request/response objects. Here's a simple logging middleware that prints the request method and URL to the console:

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next(); // Pass control to the next middleware function
});
Enter fullscreen mode Exit fullscreen mode

With middleware, you can chain together multiple functions to process requests efficiently, adding features as needed.

Step 3: Building a RESTful API

In a RESTful API, we use different HTTP methods to perform CRUD operations (Create, Read, Update, Delete). Let’s walk through how to build basic API endpoints in Express.

Create (POST Request)

We first need to enable the parsing of JSON request bodies. Express has built-in middleware for this:

app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

Next, create a simple POST route to handle creating new users:

let users = [];

app.post('/users', (req, res) => {
    const user = req.body;
    users.push(user);
    res.status(201).send(user);
});
Enter fullscreen mode Exit fullscreen mode

This endpoint will allow clients to send a JSON object containing user information, which will then be stored in the users array.

Read (GET Request)

To fetch the list of users or a specific user by ID, we can create GET routes:

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

app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');
    res.send(user);
});
Enter fullscreen mode Exit fullscreen mode

The :id syntax in the URL is a route parameter, which allows us to fetch specific users based on their ID.

Update (PUT Request)

To update an existing user’s data, we’ll use the PUT method:

app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');

    Object.assign(user, req.body); // Update the user object with new values
    res.send(user);
});
Enter fullscreen mode Exit fullscreen mode

Delete (DELETE Request)

Finally, to remove a user, we can define a DELETE route:

app.delete('/users/:id', (req, res) => {
    users = users.filter(u => u.id !== parseInt(req.params.id));
    res.status(204).send(); // 204 No Content
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Testing Your API

You can use Postman or cURL to test the API endpoints we’ve just built. Postman provides a user-friendly interface for sending HTTP requests, viewing responses, and testing your API's behavior.

Example POST request in Postman:

  • URL: http://localhost:3000/users
  • Method: POST
  • Body (JSON):
{
  "id": 1,
  "name": "John Doe",
  "email": "john@example.com"
}
Enter fullscreen mode Exit fullscreen mode

You'll get a 201 Created response with the user object you just added.

Wrapping Up

In this crash course, you learned how to set up a simple Express.js server, implement middleware, and build a complete RESTful API with CRUD operations. Express.js makes it incredibly easy to build scalable web applications, and its middleware system allows you to customize every aspect of your app.

If you want to follow along in detail, check out the full video tutorial on YouTube: Express.js Crash Course.

What’s Next?

  • Database Integration: Add MongoDB or PostgreSQL to persist data instead of using an in-memory store.
  • Error Handling: Create custom error handling middleware for better error reporting.
  • Authentication: Secure your API by adding authentication (e.g., JWT or OAuth).

Feel free to reach out with any questions or feedback in the comments below! Don’t forget to like the video, subscribe to the channel, and stay tuned for more web development tutorials.


Resources:

Top comments (0)