Node.js / Node.js REST APIs

Building a REST API with Node.js and Express

This tutorial will guide you through the process of building a REST API using Node.js and Express. You will learn how to set up a new Express project, build a few API endpoints, a…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores creating, testing, and securing RESTful APIs with Node.js and Express.

1. Introduction

In this tutorial, you'll learn how to build a REST API using Node.js and Express. The goal is to set up a new Express project, build a few API endpoints, and then test them using Postman.

By the end of this tutorial, you'll be able to:
- Set up an Express project
- Create REST API endpoints
- Test API endpoints using Postman

Prerequisites:
- Basic understanding of JavaScript
- Node.js and npm installed on your system
- Postman installed for testing API endpoints

2. Step-by-Step Guide

First, you need to install Express and set up a new project. Open your terminal and navigate to the directory where you want to create your project. Then, run the following commands:

mkdir express-api
cd express-api
npm init -y
npm install express

Now, let's create a new file called index.js. This file will serve as the main entry point for our application.

// index.js

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

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

app.listen(port, () => console.log(`Server is running on port ${port}`));

In the above code, we first import the Express module. We then create an Express application using the express() function. We define a route handler for the path '/' that gets called when we send a GET request to our server. The server is set to listen on port 3000.

3. Code Examples

Now, let's add some more endpoints to our API.

// index.js

app.get('/users', (req, res) => {
  const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
  ];
  res.json(users);
});

app.post('/users', (req, res) => {
  // in real application, you'll receive data via req.body
  const user = { id: 3, name: 'Doe' };
  res.status(201).json(user);
});

In the above example, we've added two new endpoints. The GET /users endpoint responds with a list of users, and the POST /users endpoint simulates creating a new user. In a real-world application, you'd receive the data via req.body.

4. Summary

In this tutorial, we have learned how to set up an Express project and create REST API endpoints. We also learned how to simulate the creation of a new resource with a POST request.

As next steps, you might want to explore how to connect your API to a database, and how to handle different types of HTTP methods like PUT and DELETE.

5. Practice Exercises

  1. Extend the /users endpoint to return a single user by ID.
  2. Add a DELETE /users/:id endpoint to delete a user by ID.
  3. Connect your API to a database (like MongoDB or PostgreSQL).

Remember, the best way to learn is by doing, so make sure to try out these exercises and experiment with the code. Good luck!

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

Image Converter

Convert between different image formats.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

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