Building a REST API with Node.js and Express

Tutorial 1 of 5

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!