DEV Community

CodeWithDhanian
CodeWithDhanian

Posted on

Learn HTTP & RESTful API Design

HTTP (Hypertext Transfer Protocol) is the application-layer communication protocol that allows clients and servers to exchange information across a network. Every modern web application, mobile application, backend service, microservice, and cloud platform relies on HTTP to send requests and receive responses.

A RESTful API (Representational State Transfer Application Programming Interface) is a collection of HTTP endpoints that expose resources using predictable URLs, standard HTTP methods, meaningful status codes, and structured JSON responses.

Unlike direct database access, clients never communicate with databases. Every interaction passes through a backend API where validation, authentication, authorization, business logic, and security are enforced.

Client–Server Architecture

Every HTTP request follows a predictable path.

+-------------------+
| Client            |
| Browser / Mobile  |
+---------+---------+
          |
          | HTTP Request
          v
+---------+---------+
| Web Server        |
| Nginx / Apache    |
+---------+---------+
          |
          |
          v
+---------+---------+
| Backend API       |
| Express / Django  |
| Spring Boot       |
+---------+---------+
          |
          |
          v
+---------+---------+
| Business Logic    |
+---------+---------+
          |
          |
          v
+---------+---------+
| Database          |
| PostgreSQL/MySQL  |
+-------------------+
Enter fullscreen mode Exit fullscreen mode

The client only knows how to call the API. The backend decides how data is processed, where it is stored, and what response should be returned.

HTTP Request Structure

Every HTTP request contains several important parts.

GET /users/15 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhb...
Content-Type: application/json
Accept: application/json
Enter fullscreen mode Exit fullscreen mode

Request Line

Defines:

  • HTTP Method
  • Resource Path
  • HTTP Version

Example

GET /users/15 HTTP/1.1
Enter fullscreen mode Exit fullscreen mode

Headers

Headers provide additional information.

Authorization: Bearer TOKEN
Content-Type: application/json
Accept: application/json
User-Agent: Chrome
Enter fullscreen mode Exit fullscreen mode

Examples:

  • Authorization → identifies the authenticated user.
  • Content-Type → tells the server what format the body uses.
  • Accept → tells the server which response formats are acceptable.

Body

Only requests like POST, PUT, and PATCH usually include a body.

{
    "name": "Alice",
    "email": "alice@example.com"
}
Enter fullscreen mode Exit fullscreen mode

The backend parses this JSON before validating it.

HTTP Response Structure

Example response:

HTTP/1.1 200 OK

Content-Type: application/json
Enter fullscreen mode Exit fullscreen mode
{
    "id": 15,
    "name": "Alice",
    "email": "alice@example.com"
}
Enter fullscreen mode Exit fullscreen mode

A response contains:

  • Status Line
  • Headers
  • Body

HTTP Methods

REST maps different operations to different HTTP methods.

Method Purpose
GET Retrieve data
POST Create a resource
PUT Replace an entire resource
PATCH Update specific fields
DELETE Remove a resource

Example resource:

/users
Enter fullscreen mode Exit fullscreen mode

Operations become

GET    /users
GET    /users/15

POST   /users

PUT    /users/15

PATCH  /users/15

DELETE /users/15
Enter fullscreen mode Exit fullscreen mode

Each endpoint performs exactly one responsibility.

REST Resource Design

REST is resource-oriented, not action-oriented.

Good

/users
/products
/orders
/invoices
Enter fullscreen mode Exit fullscreen mode

Poor

/createUser
/getUsers/deleteUser
/updateUser
Enter fullscreen mode Exit fullscreen mode

Resources should be represented as nouns, while the HTTP method describes the action.

URL Hierarchy

Well-designed URLs represent relationships.

/users

/users/15

/users/15/orders

/users/15/orders/8
Enter fullscreen mode Exit fullscreen mode

The URL itself explains the resource hierarchy.

Building a REST API with Express

const express = require("express");

const app = express();

app.use(express.json());

let users = [
    {
        id: 1,
        name: "Alice",
        email: "alice@example.com"
    }
];
Enter fullscreen mode Exit fullscreen mode

The server:

  • enables JSON parsing
  • stores sample data
  • exposes REST endpoints

GET

app.get("/users", (req, res) => {
    res.json(users);
});
Enter fullscreen mode Exit fullscreen mode

Returns every user.

GET by ID

app.get("/users/:id", (req, res) => {

    const user = users.find(
        u => u.id === Number(req.params.id)
    );

    if (!user) {
        return res.status(404).json({
            message: "User not found"
        });
    }

    res.json(user);
});
Enter fullscreen mode Exit fullscreen mode

The route parameter

:id
Enter fullscreen mode Exit fullscreen mode

captures the requested resource identifier.

POST

app.post("/users", (req, res) => {

    const user = {
        id: users.length + 1,
        name: req.body.name,
        email: req.body.email
    };

    users.push(user);

    res.status(201).json(user);

});
Enter fullscreen mode Exit fullscreen mode

This endpoint:

  • receives JSON
  • creates a new resource
  • returns 201 Created

HTTP Status Codes

Every response should communicate what happened.

Code Meaning
200 OK Request succeeded
201 Created Resource created
204 No Content Success without response body
400 Bad Request Invalid client input
401 Unauthorized Authentication required
403 Forbidden Permission denied
404 Not Found Resource does not exist
409 Conflict Duplicate or conflicting data
422 Unprocessable Entity Validation failed
500 Internal Server Error Unexpected server failure

Choosing the correct status code makes APIs easier to consume and debug.


JSON Response Standards

Successful responses should remain consistent.

{
    "success": true,
    "data": {
        "id": 15,
        "name": "Alice"
    }
}
Enter fullscreen mode Exit fullscreen mode

Error responses should also follow a predictable structure.

{
    "success": false,
    "message": "Email already exists",
    "errors": [
        {
            "field": "email",
            "message": "Duplicate email"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Consistent response formats simplify frontend development and automated API integrations.

REST Design Principles

A well-designed REST API follows several fundamental principles:

  • Stateless Communication — Every request contains all information required to process it. The server does not depend on previous requests.
  • Resource-Based URLs — Endpoints represent resources instead of actions.
  • Uniform Interface — Similar resources follow the same naming and behavior patterns.
  • Standard HTTP Methods — Use GET, POST, PUT, PATCH, and DELETE according to their intended purpose.
  • Meaningful Status Codes — Responses clearly indicate whether an operation succeeded or failed.
  • JSON Payloads — Structured, language-independent data format for requests and responses.
  • Idempotency — Repeating GET, PUT, or DELETE should produce the same result without unintended side effects.

Backend Engineering eBook

Master backend engineering from fundamentals to advanced concepts with practical projects and production-ready examples:

Backend Engineering eBook: https://codewithdhanian.gumroad.com/l/ungqng

HTTP & RESTful API Design

Top comments (0)