Request & Response Structure

🔗 REST API Lesson 4 Beginner

Every HTTP interaction consists of a request sent by the client and a response returned by the server. Understanding each component of these messages is essential for building and consuming REST APIs effectively.

1 Anatomy of an HTTP Request
HTTP — Full Request Breakdown
POST /api/v1/users HTTP/1.1

# ---- REQUEST LINE ----
# Method: POST
# Path: /api/v1/users
# Protocol: HTTP/1.1

# ---- HEADERS ----
Host: api.example.com                    # Required — server hostname
Content-Type: application/json           # Body format
Accept: application/json                 # Desired response format
Authorization: Bearer eyJhbGciOiJI...    # Auth token
User-Agent: PostmanRuntime/7.36.0
X-Request-ID: 550e8400-e29b-41d4-a716   # Custom correlation header

# ---- BODY ----
{
  "name": "Balaji Nayak",
  "email": "balaji@example.com",
  "password": "SecurePass123!",
  "role": "user"
}
2 Anatomy of an HTTP Response
HTTP — Full Response Breakdown
HTTP/1.1 201 Created

# ---- STATUS LINE ----
# Protocol: HTTP/1.1
# Status Code: 201
# Reason: Created

# ---- HEADERS ----
Content-Type: application/json
Location: /api/v1/users/99               # URL of new resource
X-Request-ID: 550e8400-e29b-41d4-a716   # Echo correlation header
X-Rate-Limit-Limit: 100
X-Rate-Limit-Remaining: 99

# ---- BODY ----
{
  "success": true,
  "data": {
    "id": 99,
    "name": "Balaji Nayak",
    "email": "balaji@example.com",
    "role": "user",
    "createdAt": "2026-07-13T10:30:00Z"
  },
  "message": "User created successfully"
}
3 Consistent Response Envelope
JSON — Standard Response Shape
// Success response
{
  "success": true,
  "data": { ... },
  "meta": { "page": 1, "total": 240, "limit": 20 }
}

// List response
{
  "success": true,
  "data": [ ... ],
  "meta": { "count": 20, "total": 240, "page": 1 }
}

// Error response
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The email field is required.",
    "fields": { "email": "This field is required" }
  }
}
4 Code Challenge
Challenge: Design a consistent JSON response envelope for your API. Write a Node.js/Express utility function sendSuccess(res, data, meta) and sendError(res, statusCode, message, code) that formats all responses uniformly.