In this tutorial, we will explore how to build a RESTful API using Express.js. APIs (Application Programming Interfaces) are used to allow different software systems to communicate with each other. Express.js is a web application framework for Node.js, designed to build web applications and APIs.
Express.js is a Node.js package; therefore, we will be using npm (Node Package Manager) to install it. If you haven't installed Node.js, you can download it here.
# Create a new directory and initialize it with npm init
mkdir express-api && cd express-api
npm init -y
# Install express
npm install express
Express.js uses routes to handle requests. A route is a combination of a URL pattern and a HTTP method (e.g., GET, POST, PUT, DELETE).
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('App is running on http://localhost:3000');
});
We will create a /movies
GET endpoint that will return a list of movies.
let movies = [
{ id: 1, title: 'Inception', director: 'Christopher Nolan' },
{ id: 2, title: 'Interstellar', director: 'Christopher Nolan' },
];
app.get('/movies', (req, res) => {
res.json(movies);
});
We will create a /movies
POST endpoint to add a new movie.
app.use(express.json()); // Enable JSON body parsing
app.post('/movies', (req, res) => {
const newMovie = req.body;
movies.push(newMovie);
res.json(newMovie);
});
In this tutorial, we have covered:
- What REST APIs are
- How to set up Express.js
- How to build and configure an API
- How to create endpoints for CRUD operations
To continue learning, consider diving deeper into Express.js middlewares, error handling, and more advanced features. Here are some resources:
- Express.js Official Documentation
- REST API Tutorial
The endpoint should accept a movie ID and remove the corresponding movie from the list.
Create a PUT endpoint for movies
Solutions:
app.delete('/movies/:id', (req, res) => {
const { id } = req.params;
movies = movies.filter(movie => movie.id != id);
res.json({ message: 'Movie deleted' });
});
app.put('/movies/:id', (req, res) => {
const { id } = req.params;
const newMovie = req.body;
movies = movies.map(movie => movie.id == id ? newMovie : movie);
res.json(newMovie);
});
Remember to test your endpoints using tools like Postman or curl. Keep practicing and happy coding!