A well-designed API is the backbone of any modern application. This guide covers the principles, patterns, and pitfalls of RESTful API design that every backend developer should master.
// Express.js API with proper error handling and validation
import express from "express";
import { z } from "zod";
const router = express.Router();
// Validation middleware
const validate = (schema) => (req, res, next) => {
try {
schema.parse(req.body);
next();
} catch (error) {
res.status(400).json({
error: "Validation Error",
details: error.errors.map(e => ({
field: e.path.join("."),
message: e.message,
})),
});
}
};
// Pagination helper
const paginate = (query) => {
const page = Math.max(1, parseInt(query.page) || 1);
const limit = Math.min(100, Math.max(1, parseInt(query.limit) || 20));
return { skip: (page - 1) * limit, take: limit, page, limit };
};
router.get("/api/v2/posts", async (req, res) => {
const { skip, take, page, limit } = paginate(req.query);
const [posts, total] = await Promise.all([
db.post.findMany({ skip, take, orderBy: { createdAt: "desc" } }),
db.post.count(),
]);
res.json({
data: posts,
meta: {
page, limit, total,
totalPages: Math.ceil(total / limit),
hasNext: page * limit < total,
},
});
});




