Building a RESTful API with Node.js and Express
Learn how to build a clean and robust RESTful API from scratch using Node.js, Express, and best practices.
What is a REST API?
A RESTful API (Representational State Transfer Application Programming Interface) is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol, almost always HTTP. It's the most common way for web services to communicate.
Prerequisites
- Node.js installed on your machine.
- A basic understanding of JavaScript.
Step 1: Initialize Your Project
Create a new directory for your project and initialize it with npm.
mkdir my-api
cd my-api
npm init -y
Now, let's install Express, the most popular web framework for Node.js.
npm install express
Step 2: Set up the Express Server
Create a file named index.js
and add the following code to create a basic server:
// 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 listening at http://localhost:${port}`);
});
Run your server with node index.js
. You should see "Hello, World!" when you visit http://localhost:3000
in your browser.
Step 3: Define API Routes
Let's create a simple in-memory database and a few API endpoints to manage a list of users.
Update index.js
:
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET a single user by ID
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
res.json(user);
});
// POST a new user
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
You now have a basic REST API! You can test the new endpoints using tools like Postman or curl
.
Conclusion
This is just the beginning. From here, you can connect to a real database, add authentication, validation, and much more to build a production-ready API.