Introduction
Express.js is widely used for building RESTful APIs in Node.js applications. This chapter covers API creation, route handling, request validation, error handling, and best practices.
1. Setting Up an Express API
Install Express.js
npm install express
Create a Basic API Server
const express = require("express");
const app = express();
app.use(express.json()); // Middleware to parse JSON requests
app.get("/", (req, res) => {
res.send("Welcome to our API");
});
app.listen(3000, () => console.log("API Server running on port 3000"));
2. Defining API Routes
APIs typically use different HTTP methods:
- GET ā Retrieve data
- POST ā Create new data
- PUT ā Update existing data
- DELETE ā Remove data
Example: CRUD Routes
const users = [];
// Create User (POST)
app.post("/users", (req, res) => {
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user);
});
// Get All Users (GET)
app.get("/users", (req, res) => {
res.json(users);
});
// Get Single User (GET)
app.get("/users/:id", (req, res) => {
const user = users.find(u => u.id == req.params.id);
if (!user) return res.status(404).send("User not found");
res.json(user);
});
// Update User (PUT)
app.put("/users/:id", (req, res) => {
const user = users.find(u => u.id == req.params.id);
if (!user) return res.status(404).send("User not found");
user.name = req.body.name;
res.json(user);
});
// Delete User (DELETE)
app.delete("/users/:id", (req, res) => {
const index = users.findIndex(u => u.id == req.params.id);
if (index === -1) return res.status(404).send("User not found");
users.splice(index, 1);
res.send("User deleted");
});
3. Validating Requests with Express Validator
Validation ensures incoming data is correct before processing.
Install express-validator
npm install express-validator
Example: Validating User Input
const { body, validationResult } = require("express-validator");
app.post("/users",
[body("name").isLength({ min: 3 }).withMessage("Name must be at least 3 characters long")],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user);
}
);
4. Error Handling in APIs
Example: Centralized Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something went wrong!");
});
5. Best Practices for Building APIs
- Use proper status codes (200 for success, 400 for bad requests, etc.)
- Implement authentication & authorization (JWT, OAuth, etc.)
- Validate user input using express-validator
- Use environment variables for sensitive data
- Rate-limit requests to prevent abuse (express-rate-limit)
- Enable CORS for cross-origin API access
Enable CORS
npm install cors
const cors = require("cors");
app.use(cors());
š Exercises
- Create an Express API with CRUD operations for managing products.
- Add request validation for user registration (minimum username length, valid email).
- Implement error handling for missing routes.
- Secure your API with JWT authentication.
- Enable CORS and implement rate-limiting to prevent API abuse.
Conclusion
This chapter covered building APIs with Express.js, handling routes, validation, and best practices. Next, we will explore connecting APIs to databases.