Skip to main content
Express.js Tutorial
CHAPTER 14 Beginner

Building REST APIs with Express.js

Updated: May 14, 2026
25 min read

# 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:

javascript
123456
// Capturing the article ID to query the comments table
app.get('/api/articles/:articleId/comments', async (req, res) => {
    const targetArticleId = req.params.articleId;
    const comments = await Comment.find({ article: targetArticleId });
    res.json(comments);
});

6. The 6 Constraints of REST

For an API to be technically considered "RESTful," it must adhere to these computer science constraints:
  1. 1. Client-Server Architecture: The frontend UI and the backend database logic are completely separate.
  1. 2. Statelessness: The server does not remember the client. Every request must contain all the information necessary (like a JWT Token) to process it.
  1. 3. Cacheability: Responses should define if they can be cached by the client to improve performance.
  1. 4. Uniform Interface: The API uses standard HTTP verbs and predictable URLs (as detailed above).
  1. 5. Layered System: The client doesn't know if it's talking directly to the Express server, a load balancer, or a cache.
  1. 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:

javascript
123456789101112131415
// SUCCESS RESPONSE (Status 200/201)
{
    "status": "success",
    "data": {
        "id": 1,
        "name": "Alice"
    }
}

// ERROR RESPONSE (Status 400/404/500)
{
    "status": "error",
    "message": "User not found in the database",
    "data": null
}

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 the DELETE HTTP verb.

11. Exercises

  1. 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

Question 1

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?

Question 2

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?

15. FAQs

Q: I keep hearing about GraphQL. Is REST dead? A: No. GraphQL is a powerful alternative to REST created by Facebook, which solves issues like over-fetching data. However, REST remains the undisputed standard for 90% of the world's APIs. You must master REST before exploring GraphQL.

16. Summary

In Chapter 14, we stepped back from the code to focus on system architecture. We learned that REST is a universal language of constraints and conventions. By enforcing plural noun-based URLs, strictly adhering to HTTP methods for actions, standardizing our JSON wrappers, and implementing API versioning, we ensure our Express application is professional, scalable, and developer-friendly.

17. Next Chapter Recommendation

Our API is perfectly designed, but what happens when a database query fails unexpectedly and crashes the Node.js server? Proceed to Chapter 15: Error Handling and Debugging.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·