REST API Design
·Aashish

REST API Design

Here is a comprehensive breakdown of the video's content, formatted as structured notes with code examples. This will give you the full context of REST API design and act as a practical reference guide.

Comprehensive Notes: REST API Design Guide

Designing a good API interface is one of the most critical tasks for a backend engineer. By adhering to standardized conventions, you remove guesswork for consumers, reduce integration bugs, and create a scalable system.

1. The History and Core Concepts of REST

To understand why we build APIs a certain way, it helps to know the history of the web.

  • 1990: Tim Berners-Lee invents the World Wide Web, along with URIs, HTTP, and HTML.
  • The Scalability Crisis: The web grew exponentially, leading to fears that the architecture would break down under the load.
  • 1993-2000: Roy Fielding (co-founder of the Apache HTTP server) proposed architectural constraints to fix web scalability. In his 2000 PhD dissertation, he named this style REST (Representational State Transfer).

The 6 Architectural Constraints of REST

  1. Client-Server: Strict separation of concerns (frontend handles UI, backend handles data/logic).
  2. Uniform Interface: Standardized communication between components.
  3. Layered System: Architecture is hierarchical (e.g., placing a load balancer between the client and server shouldn't break functionality).
  4. Cache: Responses must be labeled as cacheable or non-cacheable to improve network efficiency.
  5. Stateless: Crucial rule. Every request must contain all the information necessary for the server to understand it. The server does not remember previous requests.
  6. Code on Demand (Optional): Servers can temporarily transfer executable code (like JavaScript) to the client.

What does "Representational State Transfer" actually mean?

  • Representational: Resources (data) can be formatted in different ways based on the client's needs (e.g., JSON for an API client, HTML for a web browser).
  • State: The current condition or attributes of a specific resource at a given moment.
  • Transfer: Moving these resource representations between the client and server using standard HTTP methods.

2. Anatomy of an API URL

An API endpoint should be readable, predictable, and hierarchical.

Standard Structure:
[https://api.example.com/v1/resources](https://api.example.com/v1/resources)

  • Scheme: https:// (Secure HTTP).
  • Subdomain/Domain: api.example.com.
  • Versioning: /v1/ (Crucial for not breaking existing clients when making major changes later).
  • Path/Resource: /books (The data you are accessing).

Golden Rules for URL Paths:

  1. Always use Plural Nouns: Even if fetching a single item, use the plural form to denote the collection.
  • Correct: /books/123
  • Incorrect: /book/123
  1. No Spaces or Underscores: Use hyphens (kebab-case) and lowercase letters for slugs.
  • Correct: /books/harry-potter
  1. Hierarchical Relationships: A forward slash / implies moving deeper into a hierarchy (e.g., from a list of books -> to a specific book ID).

3. Idempotency & HTTP Methods

Idempotency is the concept that performing an action multiple times yields the same side effect on the server as performing it just once.

MethodIdempotent?Purpose & Behavior
GET✅ YesFetch data. Calling it 1,000 times causes no changes to the server data.
PUT✅ YesReplace an entire resource. Sending the exact same payload multiple times results in the same final state.
PATCH✅ YesPartially update a resource. Updating status: "active" multiple times keeps it "active".
DELETE✅ YesRemove a resource. The first call deletes it; subsequent calls return a 404 Not Found (no new side effects are caused).
POST❌ NoCreate a new resource. Calling it 5 times creates 5 new records with different IDs.

4. The API Design Workflow

Do not start coding your backend immediately. Follow this workflow:

  1. Analyze UI Wireframes/Figma: Look at the user interface to identify the "nouns" of your system.
  2. Identify Resources: If building a Project Management App, your nouns are Organizations, Projects, and Tasks.
  3. Design DB Schema: Map those resources to database tables.
  4. Design the API Interface (Swagger/Insomnia): Define your routes, payloads, and expected responses before writing business logic.

5. Standard CRUD Endpoints & Implementation Details

Let's look at how to implement standard endpoints using an Organization resource as an example.

A. Create Resource (POST)

Endpoint: POST /organizations
Behavior: Accepts a JSON body (ignoring server-generated fields like IDs and timestamps).
Success Response: 201 Created

// Request Body
{
  "name": "Org 1",
  "description": "My first organization",
  "status": "active"
}

// Response (201 Created)
{
  "id": "abc-123",
  "name": "Org 1",
  "description": "My first organization",
  "status": "active",
  "createdAt": "2026-08-09T10:00:00Z"
}

B. List Resources (GET)

Endpoint: GET /organizations
Behavior: Fetches a collection. It must support Pagination, Sorting, and Filtering to avoid overloading the server.
Success Response: 200 OK (Even if the list is empty, return an empty array [] with a 200 status, never a 404).

// Example Request with Query Params
GET /organizations?limit=10&page=2&sortBy=name&sortOrder=asc&status=active

// Paginated Response Structure
{
  "data": [
    { "id": "abc-123", "name": "Org 1", "status": "active" },
    { "id": "def-456", "name": "Org 2", "status": "active" }
  ],
  "total": 50,
  "page": 2,
  "totalPages": 5
}

C. Get Single Resource (GET)

Endpoint: GET /organizations/:id
Behavior: Fetches a specific entity using a dynamic ID parameter.
Success Response: 200 OK
Error Response: 404 Not Found (If the ID does not exist).

D. Update Resource (PATCH)

Endpoint: PATCH /organizations/:id
Behavior: Updates specific fields provided in the payload without replacing the whole object.
Success Response: 200 OK (Returns the updated object).

// Request Body
{
  "status": "archived"
}

E. Delete Resource (DELETE)

Endpoint: DELETE /organizations/:id
Behavior: Removes the resource from the database.
Success Response: 204 No Content (Returns an empty response body because the item is gone).

F. Custom Actions (POST)

Sometimes an action doesn't fit standard CRUD (e.g., archiving an org, cloning a project, sending an email). In REST, you handle this by creating an open-ended POST endpoint with the action at the end of the URL.
Success Response: 200 OK or 201 Created depending on what happens server-side.

Endpoint: POST /organizations/:id/archive
Endpoint: POST /projects/:id/clone


6. Best Practices for Developers

To be a top-tier backend engineer, stick to these rules:

  • Provide Sane Defaults: Do not force the client to pass obvious data.

  • If page isn't passed -> default to 1.

  • If limit isn't passed -> default to 10.

  • If sortOrder isn't passed -> default to desc.

  • If a status isn't passed on creation -> default to active.

  • Be Ruthlessly Consistent: If you name a field description in one endpoint, do not name it desc in another. Use camelCase uniformly across all JSON payloads and responses.

  • Write Interactive Documentation: Use tools like Swagger (OpenAPI) so frontend engineers don't have to guess how your API works.

  • Don't Use 404s for Empty Lists: If a filter yields zero results in a GET /resources call, return 200 OK with an empty array. Reserve 404 for when a client specifically asks for an ID that doesn't exist.