intermediate#Node.js#Express#RESTful API
Building a RESTful API with Node.js and Express
Learn how to create a RESTful API using Node.js and Express, and handle CRUD operations.
Introduction to RESTful APIs
A RESTful API 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.
Step 1: Install Required Packages
Install the required packages, including express and body-parser.
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 create a new Express app.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
Step 3: Define Routes
Define routes for CRUD operations. For example, to handle GET requests, add the following code.
app.get('/users', (req, res) => {
// Handle GET request
res.json([{
id: 1,
name: 'John Doe'
}]);
});
Step 4: Handle POST Requests
Handle POST requests to create new resources.
app.post('/users', (req, res) => {
// Handle POST request
const user = req.body;
res.json(user);
});
Step 5: Run the App
Run the app by typing node app.js in your terminal.
node app.js
Use a tool like Postman to test the API.