Building your first RESTful API

Tutorial 1 of 5

1. Introduction

1.1 Goal of the Tutorial

The goal of this tutorial is to guide you in creating your first RESTful API from scratch. By the end of this tutorial, you will have built a simple API that can perform CRUD (Create, Read, Update, Delete) operations.

1.2 Learning Outcomes

You will learn how to:
- Set up a server using Node.js and Express.js
- Define API resources
- Handle HTTP requests and responses
- Use Postman for testing your API

1.3 Prerequisites

You should have a basic understanding of:
- JavaScript
- Node.js
- Express.js


2. Step-by-Step Guide

2.1 Setting Up the Server

Firstly, we need to set up a server using Node.js and Express.js. Here's how to do it:

  1. Initialize a new Node.js project by running npm init -y in the terminal.
  2. Install Express.js by running npm install express.
  3. Create a new file named server.js and add the following code:
const express = require('express'); // Import Express.js

const app = express(); // Initialize the Express app

const port = 3000; // Define the port

app.listen(port, () => { // Start the server
    console.log(`Server is running on http://localhost:${port}`);
});

2.2 Defining API Resources

To define our API resources, we will create a simple array of objects. Each object will represent a 'user' with properties 'id', 'name', and 'email'. Add the following code to server.js:

let users = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Doe', email: 'jane@example.com' },
];

3. Code Examples

3.1 Handling HTTP Requests and Responses

3.1.1 GET Request

To handle a GET request, we use the app.get() function. Here's how to return all users:

app.get('/users', (req, res) => { // Define the endpoint
    res.send(users); // Send the users array as a response
});

3.1.2 POST Request

To handle a POST request, we use the app.post() function. Here's how to add a new user:

app.post('/users', (req, res) => { // Define the endpoint
    const newUser = req.body; // Get the new user from the request body
    users.push(newUser); // Add the new user to the users array
    res.send(users); // Send the updated users array as a response
});

4. Summary

In this tutorial, you learned how to:
- Set up a server using Node.js and Express.js
- Define API resources
- Handle HTTP requests and responses

The next step would be to connect your API to a database, such as MongoDB or PostgreSQL. You can learn more about this in the Express.js Database Integration guide.


5. Practice Exercises

5.1 Exercise 1: Return a Single User

Create a GET /users/:id endpoint that returns a single user by ID.

5.2 Exercise 2: Update a User

Create a PUT /users/:id endpoint that updates a user's details.

5.3 Exercise 3: Delete a User

Create a DELETE /users/:id endpoint that removes a user from the array.

5.4 Solutions

You can find the solutions for these exercises in the Express.js Routing Guide.

Happy coding!