Description

A REST API (Representational State Transfer Application Programming Interface) is a widely adopted web service architecture that allows software applications to interact over the Internet using stateless communication. Unlike traditional RPC or SOAP-based APIs, REST emphasizes scalability, simplicity, and resource-oriented design.

Introduced by Roy Fielding in his 2000 PhD dissertation, REST is an architectural style rather than a protocol, built around six guiding constraints that ensure performance, scalability, and modifiability. It enables systems to interact via HTTP, with resources exposed via URLs and manipulated using HTTP methods like GET, POST, PUT, and DELETE.

Key Concepts and Principles

1. Resource-Oriented Architecture

At the heart of REST is the idea of resources. Resources are uniquely identifiable items—such as users, files, posts, etc.—that are represented using URIs (Uniform Resource Identifiers). For example:

GET https://api.example.com/users/42

Here, users/42 refers to a user with ID 42.

2. Statelessness

Each HTTP request must contain all the information needed to complete the operation. The server does not store session information between requests. This improves reliability and scalability but requires clients to manage their own session state (e.g., tokens).

3. Uniform Interface

REST relies on a standardized and simplified interface. This includes:

  • Use of HTTP verbs (GET, POST, PUT, DELETE, PATCH)
  • Resource identification through URIs
  • Self-descriptive messages (e.g., JSON with proper headers)
  • Hypermedia as the engine of application state (HATEOAS)

4. Client-Server Separation

Clients and servers operate independently. Clients handle the UI and user logic; servers handle business logic and data persistence. This decoupling improves flexibility and allows independent evolution.

5. Cacheability

Responses from the server must define whether they are cacheable. Caching reduces latency and network load by storing frequently accessed data on the client side.

6. Layered System

Clients may not be aware of intermediate systems (proxies, gateways, etc.) between them and the server. This allows for scalability through load balancers and caching proxies.

HTTP Methods in REST

Each HTTP method corresponds to a CRUD (Create, Read, Update, Delete) operation:

MethodActionDescription
GETReadRetrieves a representation of a resource
POSTCreateCreates a new resource
PUTUpdateUpdates an existing resource or replaces it
PATCHModifyApplies partial updates to a resource
DELETEDeleteDeletes a resource

Example:

POST /users
{
  "name": "Jane",
  "email": "[email protected]"
}

RESTful URL Design

  • Resources are nouns, not verbs.
  • URLs should be hierarchical and readable.
  • Avoid using action words like /getUser or /createUser.

Good:

GET /users
GET /users/123
POST /users
PUT /users/123
DELETE /users/123

Response Format

Most REST APIs use JSON due to its readability and ease of use.

Example Response:

{
  "id": 123,
  "name": "Jane Doe",
  "email": "[email protected]"
}

HTTP Status Codes

CodeMeaningWhen to Use
200OKSuccessful GET, PUT, or DELETE
201CreatedSuccessful POST (new resource created)
204No ContentSuccessful DELETE or empty response
400Bad RequestInvalid input or malformed request
401UnauthorizedMissing or invalid authentication
403ForbiddenValid credentials, but no permission
404Not FoundResource doesn’t exist
500Internal ErrorUnexpected server error

REST vs SOAP

FeatureRESTSOAP
ProtocolHTTPHTTP, SMTP, etc.
Message FormatJSON (commonly)XML
SimplicityLightweight and flexibleHeavy, strict standards
SecurityBasic, OAuthWS-Security, robust standards
CachingSupportedNot typically used
ToolingWide range (Postman, Swagger)WSDL-based tools

Authentication Techniques

REST APIs are stateless, so each request must be authenticated independently.

  • API Keys – Static token passed via headers or query
  • OAuth2 – Delegated access using access tokens
  • JWT – Self-contained, signed tokens
  • Basic Auth – Username/password encoded in headers (not secure)
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Pagination, Filtering, and Sorting

Best practice for listing endpoints:

GET /users?limit=25&page=2&sort=name&status=active

Include metadata in the response:

{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 25,
    "total": 400
  }
}

HATEOAS (Hypermedia as the Engine of Application State)

Encourages APIs to return links with responses:

{
  "id": 123,
  "name": "Jane Doe",
  "links": [
    { "rel": "self", "href": "/users/123" },
    { "rel": "orders", "href": "/users/123/orders" }
  ]
}

Tools for REST API Testing

ToolDescription
PostmanGUI tool for making API requests
curlCommand-line tool for HTTP requests
SwaggerOpenAPI-based documentation and testing platform
InsomniaLightweight REST client
HTTPieFriendly CLI for HTTP requests

REST in Modern Applications

  • Web Frontends: Angular, React apps interact with REST APIs.
  • Mobile Apps: iOS/Android apps sync data via REST endpoints.
  • IoT Devices: Send telemetry using REST calls.
  • Microservices: Use REST to communicate within service ecosystems.

Common Mistakes to Avoid

  • Using verbs in URLs: /createUser vs. /users
  • Not versioning the API: /v1/users
  • Ignoring status codes
  • Making APIs too chatty (too many calls)
  • Failing to document endpoints

Versioning Strategies

  • URI-based: https://api.example.com/v1/users
  • Header-based: Accept: application/vnd.example.v1+json
  • Parameter-based: ?version=1

Security Best Practices

  • Use HTTPS only
  • Validate and sanitize inputs
  • Enforce rate limiting
  • Avoid sensitive data in URLs
  • Use scopes/roles for access control
  • Rotate and revoke tokens regularly

Rate Limiting and Throttling

Prevent abuse and server overload by limiting usage:

  • 429 Too Many Requests
  • Include headers:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 57
X-RateLimit-Reset: 1609459200

Real-World Use Case: GitHub REST API

GitHub’s REST API offers endpoints like:

  • GET /repos/:owner/:repo
  • POST /repos/:owner/:repo/issues
  • PATCH /repos/:owner/:repo/issues/:number

It supports pagination, filtering, authentication, and webhooks—demonstrating a mature RESTful API.

Related Terms

  • OpenAPI Specification (formerly Swagger)
  • GraphQL – An alternative to REST for data querying
  • Webhooks – Event-driven callbacks
  • CRUD – Core operations for persistent storage
  • API Gateway – Middleware that controls access, routing, and policies
  • Idempotency – Multiple identical requests have the same effect
  • CORS – Cross-origin resource sharing for browser security