Skip to main content

Building a REST API

APIs (Application Programming Interfaces) are the backbone of modern web development. They allow different applications to communicate with each other—whether it’s your frontend talking to your backend, or third-party services integrating with your app. Think of a REST API like a restaurant menu. The menu (API documentation) tells you what dishes (resources) are available and how to order them (HTTP methods). You do not need to know how the kitchen works internally—you just place an order (request) and receive your dish (response). The waiter (HTTP) carries messages back and forth using a standardized process (the REST constraints).

What is REST?

REST (Representational State Transfer) is an architectural style for designing networked applications. It’s not a protocol or standard, but a set of constraints that, when followed, create scalable and maintainable APIs.

Core Principles of REST

HTTP Methods and Their Meanings

Why REST?

  • Universal: Works with any programming language that can make HTTP requests
  • Scalable: Statelessness allows easy horizontal scaling
  • Cacheable: GET requests can be cached for better performance
  • Simple: Uses familiar HTTP concepts developers already know
In this chapter, we will build a simple REST API to manage a list of items, demonstrating these principles in action.

Setup

Create a new file server.js and install express if you haven’t.

GET: Read Data

POST: Create Data

PUT: Update Data

DELETE: Remove Data

Testing with Postman / Insomnia

Since we don’t have a frontend yet, use tools like Postman or Insomnia to test your API.
  1. GET http://localhost:5000/api/items -> Should return list.
  2. POST http://localhost:5000/api/items with JSON body {"name": "New Item"} -> Should add item.
  3. PUT http://localhost:5000/api/items/1 with JSON body {"name": "Updated Item"} -> Should update item 1.
  4. DELETE http://localhost:5000/api/items/1 -> Should delete item 1.

Summary

  • REST APIs use standard HTTP methods for CRUD operations
  • GET for retrieving data (should never modify server state)
  • POST for creating data (return 201, not 200)
  • PUT for full replacement, PATCH for partial update
  • DELETE for removing data (return 204 No Content for success)
  • Always validate input and handle errors—never trust data from the client
  • Use proper HTTP status codes: they are part of the API contract, not decoration

Request Validation with Joi

Never trust client input! Validate all requests:

API Response Standards

Maintain consistent response formats:

Pagination

Filtering and Sorting

HTTP Status Codes Reference

API Versioning

Complete REST Controller Example