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.
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
You should have a basic understanding of:
- JavaScript
- Node.js
- Express.js
Firstly, we need to set up a server using Node.js and Express.js. Here's how to do it:
npm init -y
in the terminal.npm install express
.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}`);
});
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' },
];
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
});
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
});
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.
Create a GET /users/:id
endpoint that returns a single user by ID.
Create a PUT /users/:id
endpoint that updates a user's details.
Create a DELETE /users/:id
endpoint that removes a user from the array.
You can find the solutions for these exercises in the Express.js Routing Guide.
Happy coding!