In this tutorial, you will learn how to create a simple REST API with Node.js and Express. A REST API allows your application to communicate with other systems and handle HTTP requests to get, post, update, or delete data.
Node.js Building a REST API
1. Setting Up the Project
Note: If you have already set up the project and installed the required dependencies in a previous tutorial, you can skip this step and proceed with the next part of the tutorial.
First, set up a new Node.js project and install the necessary dependencies:
mkdir rest-api
cd rest-api
npm init -y
npm install express
This creates a project directory, initializes a new Node.js project, and installs Express, a minimal and flexible Node.js web application framework.
2. Creating the API
Create a file called `app.js` to define your REST API routes:
const express = require('express');
const app = express();
// Sample data
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' }
];
// GET route to fetch all users
app.get('/users', (req, res) => {
res.json(users);
});
// POST route to add a new user
app.post('/users', (req, res) => {
const user = req.body; // Assume that body parsing middleware is used
users.push(user);
res.status(201).json(user);
});
// PUT route to update a user
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id == req.params.id);
if (user) {
user.name = req.body.name;
res.json(user);
} else {
res.status(404).send('User not found');
}
});
// DELETE route to remove a user
app.delete('/users/:id', (req, res) => {
const index = users.findIndex(u => u.id == req.params.id);
if (index !== -1) {
users.splice(index, 1);
res.status(204).send();
} else {
res.status(404).send('User not found');
}
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
This code defines GET, POST, PUT, and DELETE routes for managing users. The `app.get()`
route fetches the users, `app.post()`
adds a new user, `app.put()`
updates an existing user, and `app.delete()`
removes a user.
3. Running the API
Start the server by running the following command in your terminal:
node app.js
Once the server is running, you can test your API using a tool like Postman or by sending HTTP requests from your frontend application.
4. Conclusion
Now you've built a simple REST API using Node.js and Express. This API can handle basic CRUD operations, and you can expand it by adding more routes and features based on your application needs.