What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a set of rules that allows applications to communicate with each other. It uses HTTP methods like GET, POST, PUT, and DELETE to perform operations on data.
Why Use Node.js and Express.js?
Node.js is a popular runtime environment for running JavaScript on the server side. Express.js is a lightweight and flexible Node.js framework that simplifies the process of building APIs.
- Node.js: Asynchronous, event-driven, and scalable.
- Express.js: Provides routing and middleware functionalities for efficient API development.
Step-by-Step Guide to Building a REST API
1. Set Up Your Environment
To get started, ensure you have Node.js installed. You can download it from Node.js official website.
// Verify Node.js installation
node -v
npm -v
2. Create a New Project
Initialize a new Node.js project:
// Create a new directory and navigate to it
mkdir rest-api-tutorial
cd rest-api-tutorial
// Initialize npm
npm init -y
3. Install Express.js
Install the Express.js package:
// Install Express.js
npm install express
4. Write Your First API Endpoint
Create a file named server.js
and add the following code:
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON
app.use(express.json());
// Define a basic GET endpoint
app.get('/', (req, res) => {
res.send('Welcome to the REST API!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Run your application:
node server.js
Open your browser and navigate to http://localhost:3000.
5. Create More Endpoints
Add more routes for CRUD operations. For example:
// Sample data
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
// GET all users
app.get('/users', (req, res) => {
res.json(users);
});
// POST a new user
app.post('/users', (req, res) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser);
});
// PUT to update a user
app.put('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const updatedUser = req.body;
users = users.map(user => (user.id === id ? updatedUser : user));
res.json(updatedUser);
});
// DELETE a user
app.delete('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
users = users.filter(user => user.id !== id);
res.status(204).send();
});
Testing Your API
Use tools like Postman or Hoppscotch to test your API endpoints.
Conclusion
Congratulations! You’ve built a basic REST API using Node.js and Express.js. Keep exploring advanced topics like authentication, database integration, and error handling to enhance your skills.