In this tutorial, you’ll learn how to build a REST API using Express.js. Express.js is a lightweight and flexible web framework for Node.js. It’s popular for creating APIs quickly and efficiently. By the end, you’ll have a working API and understand the basics of how it works.
What is a REST API?
A REST API allows applications to communicate over the web. REST stands for Representational State Transfer. It follows simple principles:
- Stateless: Each request stands alone. No server memory is used for past requests.
- Client-Server: The client (browser or app) and server stay independent.
- Resource-Based: Each URL represents a resource (e.g.,
/users
).
REST APIs are widely used because they are easy to understand and work with.
Why Use Express.js for REST APIs?
Express.js makes building REST APIs easier.
- Simple: It’s minimal, so you use only what you need.
- Flexible: You can add middleware to handle tasks like logging or parsing data.
- Fast: With fewer features baked in, it runs efficiently.
Developers often pick Express.js because it’s great for small and large projects alike.
Setting Up Your Development Environment
Prerequisites
Before starting, make sure you have:
- Node.js installed: Download it from Node.js official site.
- Basic JavaScript knowledge: Understand functions, objects, and ES6 syntax.
Installing Express.js
- Open a terminal.
- Run
npm install express
to add Express.js to your project.
Project Structure
Organize your project files as shown:
project-folder/
├── node_modules/
├── package.json
├── app.js
The app.js
file will hold the API code.
Building Your First REST API
- Initialize Your Project
Run npm init -y
in your terminal. This creates a package.json
file.
- Create a Basic Server
Add the following code in app.js
:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
- Add Routes
Add API endpoints for different HTTP methods:
app.get('/users', (req, res) => res.json({ message: 'Get all users' }));
app.post('/users', (req, res) => res.json({ message: 'Create a user' }));
app.put('/users/:id', (req, res) => res.json({ message: `Update user ${req.params.id}` }));
app.delete('/users/:id', (req, res) => res.json({ message: `Delete user ${req.params.id}` }));
- Use Middleware
Middleware processes requests before they reach your routes. Add this to handle JSON data:
app.use(express.json());
Connecting to a Database
For this tutorial, we will use MongoDB. Install the library with:
npm install mongoose
Then connect to a MongoDB database:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
Testing Your API
- Use Postman
Postman is a tool to test APIs. Download it from Postman’s website.
- Create a new request.
- Enter your API URL (e.g.,
http://localhost:3000/users
). - Send requests to test endpoints.
- Automated Tests
Write tests with a library like Jest. Example:
test('GET /users', async () => {
const response = await request(app).get('/users');
expect(response.statusCode).toBe(200);
});
Best Practices for REST APIs
Follow these tips to make your API better:
- Use clear endpoint names: Stick to nouns like
/users
or/products
. - Handle errors: Send meaningful messages for errors.
- Secure your API: Use tools like JSON Web Tokens (JWT) for authentication.
- Optimize responses: Cache data or paginate large results.
Common Challenges
- Debugging routes: Double-check your URLs and methods.
- Managing middleware: Keep it simple. Too many layers slow down performance.
- Scaling: Add a load balancer for heavy traffic.
Conclusion
You’ve built a REST API using Express.js. You learned about routes, middleware, and testing. Explore more by adding features like user authentication or deploying your API. Share your feedback in the comments or try building your own project!
Previous Lesson
Day 25: Introduction to Express.js
Next Lesson
Day 27: Connecting Node.js to a Database
Pingback: Express.js - Equitem
Pingback: Connect Node.js to a Database - Equitem