Building REST APIs with Express.js
# CHAPTER 14
Building REST APIs with Express.js
1. Introduction
Throughout this tutorial, we have built APIs that return JSON data. But what makes an API a REST API? REST (Representational State Transfer) is not a technology or a package you install; it is a strict set of architectural rules and design conventions. When backend engineers follow these rules, their APIs become predictable, scalable, and incredibly easy for frontend developers to consume. In this chapter, we will solidify our understanding of REST principles and review how to architect a perfect Express endpoint.2. Learning Objectives
By the end of this chapter, you will be able to:- Define the constraints of REST architecture.
- Follow proper naming conventions for API routes.
- Align HTTP methods with specific CRUD actions.
- Structure JSON responses uniformly.
3. Beginner-Friendly Explanation
Imagine a library system (REST Architecture). A good library has strict rules. Every book is categorized the exact same way. The signs are clear (Fiction, Non-Fiction, Biographies). If you learn how one library works, you can walk into any library in the world and find a book. A bad library just throws books into random piles on the floor. When you build an API using random URLs like/get-the-users and /delete-this-post-now, you are throwing books on the floor. A REST API enforces strict URL rules (like /api/users) so that any developer in the world instantly knows how to interact with your system without reading a manual.
4. The Rules of REST Naming Conventions
Endpoints must be Noun-based (Resources), not Verb-based (Actions). The HTTP method itself provides the Verb. Furthermore, nouns should always be Plural.BAD Examples (Non-RESTful):
-
GET /api/getAllArticles
-
POST /api/createArticle
-
DELETE /api/deleteArticle/5
-
PUT /api/updateArticle/5
GOOD Examples (RESTful):
-
GET /api/articles(Get all)
-
POST /api/articles(Create new)
-
GET /api/articles/5(Get specific article)
-
PUT /api/articles/5(Update specific article)
-
DELETE /api/articles/5(Delete specific article)
*Notice the elegance? It is the exact same URL (/api/articles). The HTTP Method tells the server what action to perform.*
5. Nested Resources
How do you structure the URL if you want to find all the comments belonging to a specific article? You nest the resources logically.RESTful Route:
GET /api/articles/5/comments
*(Translation: Find Article #5, and give me all its Comments).*
Express Implementation:
6. The 6 Constraints of REST
For an API to be technically considered "RESTful," it must adhere to these computer science constraints:- 1. Client-Server Architecture: The frontend UI and the backend database logic are completely separate.
- 2. Statelessness: The server does not remember the client. Every request must contain all the information necessary (like a JWT Token) to process it.
- 3. Cacheability: Responses should define if they can be cached by the client to improve performance.
- 4. Uniform Interface: The API uses standard HTTP verbs and predictable URLs (as detailed above).
- 5. Layered System: The client doesn't know if it's talking directly to the Express server, a load balancer, or a cache.
- 6. Code on Demand (Optional): The server can send executable code to the client.
7. Standardizing JSON Responses
A REST API should never surprise the frontend developer. If an error occurs, the structure of the JSON should look identical to the structure of a success, just with different values.The Professional Response Wrapper:
8. Backend Workflow: Versioning
What happens if you have a mobile app installed on 1 million phones using your API, and you want to completely change how the database works? If you change the code, all 1 million old apps will instantly crash. Professional REST APIs use Versioning.Always prefix your routes with /api/v1/.
app.use('/api/v1/users', userRoutes);
When you make breaking changes a year later, you build /api/v2/users. The old phones keep hitting v1 and functioning perfectly, while the new app update hits v2.
9. Best Practices
-
Use the correct HTTP Status Codes: Don't just return
res.json({ error: "Failed" })while leaving the HTTP Status Code as 200 OK. If it is an error, use a 4xx or 5xx status code. Frontend libraries like Axios rely on the physical HTTP Status Code to trigger their error handling logic.
10. Common Mistakes
-
Using GET to delete data: Beginners sometimes write
app.get('/api/users/delete/:id')because it's easy to trigger from a browser address bar. This violates REST principles entirely. Web crawlers (like Googlebot) follow GET links automatically. If Googlebot crawled your site, it would click all the GET links and accidentally delete your entire database! Always use theDELETEHTTP verb.
11. Exercises
-
1.
Critique this API endpoint:
POST /api/v1/user/update-profile/42. Rewrite it to conform perfectly to REST architectural naming conventions.
12. Coding Challenges
- Challenge: Design the URL endpoints for an E-commerce system. Write down the 5 RESTful URLs and their associated HTTP methods to handle CRUD operations for a "products" resource. Then, write a 6th URL to retrieve all "reviews" for a specific product.
13. MCQs with Answers
According to RESTful API naming conventions, which of the following is the correct endpoint design to retrieve a specific user with the ID of 99?
What does the "Stateless" constraint mean in REST architecture?
14. Interview Questions
- Q: Explain the concept of RESTful architecture. What specific constraints must an API adhere to in order to be considered truly RESTful?
-
Q: Why is API versioning (e.g.,
/api/v1/) considered a mandatory best practice in enterprise software development? What disaster does it prevent?