Node.js / Node.js Express Framework

Building REST APIs with Express

In this tutorial, you'll learn how to build a RESTful API using Express. This involves creating routes that correspond to the standard HTTP methods and defining the appropriate be…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers building web applications and REST APIs using the Express framework.

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();
});

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Name Generator

Generate realistic names with customizable options.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help