Building REST APIs with Express

Tutorial 4 of 5

Building REST APIs with Express Tutorial

Introduction

In this tutorial, you will learn how to build a RESTful API using Express. Express is a fast, unopinionated, and minimalist web framework for Node.js, and it's a great tool for creating APIs.

You will learn how to:

  • Set up an Express server
  • Define routes that correspond to the standard HTTP methods (GET, POST, PUT, DELETE)
  • Handle HTTP requests and send responses
  • Use middleware for request processing

Prerequisites:
- Basic knowledge of JavaScript
- Node.js and NPM installed on your computer
- Familiarity with HTTP methods would be beneficial

Step-by-Step Guide

  1. Setting up Express server

    First, we need to install Express. In your project folder, run the following command:

    bash npm install express --save

    To set up an Express server, we need to require the express module and instantiate it.

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

  2. Defining Routes

    Routes are defined using methods of the Express app object that correspond to HTTP methods. For example, app.get() handles GET requests and app.post() handles POST requests.

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

    Here, we're defining a route for the root URL ("/") and we're sending 'Hello World!' as a response.

  3. Handling Requests and Sending Responses

    In the route handler function, Express provides a request object (req) and a response object (res). We can use these to access request data and send responses.

    javascript app.get('/users/:id', function (req, res) { const id = req.params.id; res.send(`User ID is: ${id}`); });

    In this route, we're accessing a URL parameter (id) from the request and sending it in the response.

  4. Using Middleware

    Middleware functions can perform actions on the request and response objects, or execute any code needed. They can also end the request-response cycle or call the next middleware in the stack.

    javascript app.use(function (req, res, next) { console.log('Time:', Date.now()); next(); });

    This middleware logs the current time for every request.

Code Examples

  1. Basic Express Server

    Here's a simple Express server that responds to a GET request at the root URL.

    ```javascript
    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}/);
    });
    ```

  2. Handling Different HTTP Methods

    This example shows how to handle different HTTP methods at the same route.

    ```javascript
    app.get('/users', (req, res) => {
    res.send('Got a GET request at /users');
    });

    app.post('/users', (req, res) => {
    res.send('Got a POST request at /users');
    });

    app.put('/users', (req, res) => {
    res.send('Got a PUT request at /users');
    });

    app.delete('/users', (req, res) => {
    res.send('Got a DELETE request at /users');
    });
    ```

Summary

In this tutorial, we covered the basics of building a RESTful API using Express. We learned how to set up an Express server, define routes, handle requests and responses, and use middleware.

For further learning, take a deeper look into middleware, learn how to use Express with a database, or explore other Express features.

Practice Exercises

  1. Create an Express server that responds to a GET request at "/about" with your own message.
  2. Add a route to your server that accepts POST requests at "/user" and sends a response with the message "Creating a new user".
  3. Create a middleware that logs the request method and URL for every request to the server.

Solutions:

app.get('/about', (req, res) => {
  res.send('This is the about page.');
});
app.post('/user', (req, res) => {
  res.send('Creating a new user');
});
app.use((req, res, next) => {
  console.log(`Request method: ${req.method}`);
  console.log(`Request URL: ${req.url}`);
  next();
});