Building a RESTful API with Node.js and Express
Learn how to build a RESTful API using Node.js and Express, and understand the basics of API design.
Introduction to RESTful APIs
A RESTful API (Application Programming Interface) is an architectural style for designing networked applications. It is based on the idea of resources, which are identified by URIs, and can be manipulated using a fixed set of operations.
Step 1: Install Required Packages
First, you need to install the required packages. Run the following command in your terminal:
npm install express body-parser
Step 2: Create a New Express App
Create a new file called app.js and add the following code to it:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const port = 3000;
Step 3: Define API Endpoints
Define API endpoints for creating, reading, updating, and deleting resources. For example, let's say we want to manage a list of books. We can define the following endpoints:
let books = [
{ id: 1, title: 'Book 1', author: 'Author 1' },
{ id: 2, title: 'Book 2', author: 'Author 2' }
];
app.get('/books', (req, res) => {
res.json(books);
});
app.get('/books/:id', (req, res) => {
const id = req.params.id;
const book = books.find((book) => book.id === parseInt(id));
if (!book) {
res.status(404).json({ message: 'Book not found' });
} else {
res.json(book);
}
});
app.post('/books', (req, res) => {
const { title, author } = req.body;
const newBook = { id: books.length + 1, title, author };
books.push(newBook);
res.json(newBook);
});
app.put(, {
id = req..;
book = books.( book. === (id));
(!book) {
res.().({ : });
} {
{ title, author } = req.;
book. = title;
book. = author;
res.(book);
}
});
app.(, {
id = req..;
index = books.( book. === (id));
(index === -) {
res.().({ : });
} {
books.(index, );
res.({ : });
}
});
Step 4: Start the Server
Start the server by running the following command in your terminal:
node app.js
You can now use a tool like curl or a REST client to test your API endpoints.