Building a RESTful API with Node.js and Express
Learn how to build a RESTful API using Node.js and Express, and create a simple API for managing books.
Introduction to RESTful APIs
A RESTful API (Application Programming Interface) is an architectural style for designing networked applications. It's based on the idea of resources, which are identified by URIs, and can be manipulated using a fixed set of operations.
Installing Dependencies
To build a RESTful API using Node.js and Express, you need to have Node.js and npm installed on your computer. You also need to install the Express.js framework and the body-parser middleware. You can install these dependencies by running the following command:
npm install express body-parser
Creating a Server
To create a server, you can use the following code:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.get('/books', (req, res) => {
const books = [
{ id: 1, title: 'Book 1', author: 'Author 1' },
{ id: 2, title: 'Book 2', author: 'Author 2' }
];
res.json(books);
});
app.post('/books', (req, res) => {
const book = req.body;
console.log(book);
res.send('Book created successfully');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
You can run this code by saving it to a file called server.js and running the following command:
node server.js
You can then access your API by navigating to http://localhost:3000/books in your web browser.