Introduction
REST (Representational State Transfer) is an architectural style for designing networked APIs. A RESTful API models data as resources (nouns, not verbs) that are manipulated using standard HTTP methods. In Express, following REST conventions makes your API predictable, easy to document, and easy for other developers to consume without reading extensive documentation.
Cricket analogy: REST modeling data as resources is like a scorecard treating 'batsmen', 'bowlers', and 'innings' as nouns you look up, not verbs like 'batBall' or 'bowlOver'; standard HTTP methods act on these the way standard scoring actions (run, wicket, extra) apply consistently to any match.
Syntax
// Resource-based routes for a 'users' resource
app.get('/users', getAllUsers); // list
app.get('/users/:id', getUserById); // read one
app.post('/users', createUser); // create
app.put('/users/:id', replaceUser); // full update
app.patch('/users/:id', updateUser); // partial update
app.delete('/users/:id', deleteUser); // deleteExplanation
Good REST design uses plural nouns for collection URLs (/users, not /getUsers), nests resources logically (/users/:id/orders), and relies on the HTTP method to express the action rather than encoding verbs in the URL. Responses should use accurate status codes: 200 OK for successful reads/updates, 201 Created for successful creation, 204 No Content when there is no response body, 400 Bad Request for invalid client input, 401/403 for auth failures, 404 Not Found for missing resources, and 500 Internal Server Error for unexpected server failures.
Cricket analogy: Using /players not /getPlayers, and nesting /teams/:id/matches, is like a scorecard labeling sections by role, not action; a completed run-out review returns 200, a new match record returns 201, and a request for a nonexistent player ID returns 404.
Example
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'name and email are required' });
}
const newUser = { id: Date.now(), name, email };
users.push(newUser);
res.status(201).json(newUser);
});
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.status(200).json(user);
});Output
POST /users with a valid body returns 201 Created with the new user JSON in the response. GET /users/999 for a non-existent id returns 404 Not Found with an error message, letting the client distinguish between a successful lookup and a missing resource without inspecting the body.
Cricket analogy: POST /players with a valid body returns 201 Created with the new player's profile JSON, like registering a debutant; GET /players/999 for a retired player's old squad number returns 404 Not Found, letting the scorer distinguish a real lookup from a missing record.
Key Takeaways
- Model URLs around resources (nouns), not actions (verbs).
- Use HTTP methods (GET, POST, PUT, PATCH, DELETE) to express intent.
- Return accurate status codes: 200, 201, 204, 400, 404, 500.
- Use plural resource names and nest related resources logically.
- Keep responses consistent in shape (e.g., always JSON with predictable fields).
Practice what you learned
1. Which URL best follows RESTful resource-based conventions for fetching a single blog post?
2. What status code should a successful POST request that creates a new resource return?
3. Which HTTP method is conventionally used for a partial update of a resource?
4. What status code should be returned when a client requests a resource that does not exist?
5. In REST design, what does the DELETE method typically map to?
Was this page helpful?
You May Also Like
Routing in Express
Understand how Express matches HTTP methods and URL paths to handler functions using routes.
Route Parameters and Query Strings
Understand how to capture dynamic URL segments and optional query data in Express routes.
CRUD Operations in Express
Build complete Create, Read, Update, and Delete route handlers in Express using a database model.
API Versioning and Best Practices
Learn common strategies for versioning Express APIs and best practices for building maintainable endpoints.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics