How REST APIs Work
BeginnerA REST API is a set of rules for how two computers communicate over HTTP. When your app needs data from a server — user profiles, product listings, order history — it sends an HTTP request to a URL endpoint. The server processes it and sends back structured data (almost always JSON). REST is the dominant architectural style for web APIs because it is stateless, cacheable, and maps naturally onto HTTP verbs.
Think of it like ordering at a restaurant
You (the client) look at the menu (API documentation) and tell the waiter (HTTP request) what you want. The waiter takes your order to the kitchen (server), which prepares your food (processes the request) and sends it back via the waiter (HTTP response). You don't need to know how the kitchen works — you just need to know what to order and what format the food will arrive in.
Step by Step
Key Concepts
HTTP Methods
GET: retrieve a resource (safe, idempotent, no body). POST: create a resource (not idempotent — calling twice creates two resources). PUT: replace a resource entirely (idempotent). PATCH: partially update a resource. DELETE: remove a resource (idempotent). The method signals intent to both the server and any intermediaries (caches, proxies).
HTTP Status Codes
1xx: informational. 2xx: success (200 OK, 201 Created, 204 No Content). 3xx: redirects (301 Moved Permanently, 304 Not Modified). 4xx: client errors (400 Bad Request, 401 Unauthorised, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests). 5xx: server errors (500 Internal Server Error, 503 Service Unavailable).
Statelessness
Every HTTP request must contain all information needed to process it. The server holds no session state between requests. This is what makes REST scalable — any server instance can handle any request without coordination. Authentication state is passed in every request via a token (Authorization header), not stored server-side.
JSON (JavaScript Object Notation)
The universal data format for REST APIs. A lightweight text format with objects ({}), arrays ([]), strings, numbers, booleans, and null. APIs return JSON in the response body; clients send JSON in POST/PUT/PATCH request bodies with Content-Type: application/json header.
Authentication vs Authorisation
Authentication: verifying who you are (validating a JWT token, API key, or OAuth token). Authorisation: verifying what you're allowed to do (can this user edit this resource?). Auth failures return 401 (not authenticated) or 403 (authenticated but not authorised).
Idempotency
An operation is idempotent if calling it multiple times produces the same result as calling it once. GET, PUT, DELETE are idempotent. POST is not — POSTing twice creates two resources. Idempotent operations are safe to retry on network failure. APIs often provide idempotency keys for non-idempotent operations like payment processing.
CORS (Cross-Origin Resource Sharing)
Browsers block JavaScript from calling APIs on a different domain by default (same-origin policy). CORS is an HTTP header mechanism that tells the browser which origins are allowed to make requests. The server sets Access-Control-Allow-Origin headers; the browser checks them before allowing the request.
API Versioning
APIs change over time, but existing clients break if you change response shapes. Common strategies: URL versioning (/api/v1/users vs /api/v2/users), header versioning (Accept: application/vnd.api+json;version=2), or query param (?version=2). URL versioning is most common and explicit.
Key Facts
- REST (Representational State Transfer) was defined by Roy Fielding in his 2000 PhD dissertation. It is not a protocol — it is a set of architectural constraints on top of HTTP.
- The Twitter API serves over 300 million API calls per day. Each tweet you see on a third-party app is one or more API calls.
- HTTP/2 can multiplex up to 100+ concurrent requests over a single TCP connection. HTTP/1.1 required separate connections or queued requests, causing head-of-line blocking.
- JWT (JSON Web Token) is the most common auth mechanism for REST APIs. It encodes user identity + claims in a signed, base64-encoded string — the server can verify it without a database lookup.
- GraphQL was invented by Facebook in 2012 to solve REST's over-fetching and under-fetching problems. Instead of multiple endpoints, clients send a query describing exactly what data they need.
- Rate limiting is almost universal in public APIs. The HTTP 429 Too Many Requests response includes a Retry-After header telling you when to try again.
Real-World Applications
Building a mobile app backend
A mobile app calls REST APIs for every screen: GET /products for the product list, POST /cart/items to add to cart, POST /orders to checkout. Each endpoint is stateless — the app sends the user's JWT token in every request, so any backend server can handle any request without session affinity.
Third-party integrations
When your app sends a Slack notification, charges a Stripe payment, or sends a Twilio SMS, it's calling REST APIs. These are POST requests with JSON payloads and an API key in the Authorization header. Webhook callbacks are the reverse: Stripe calls your API when a payment succeeds.
Microservices communication
Internal services communicate via REST or gRPC. Order Service calls Inventory Service GET /products/123/stock before confirming an order. This synchronous inter-service communication is one of the patterns that make microservices possible — but over-using synchronous calls creates tight coupling and latency chains.
API pagination
Endpoints that return lists use pagination to avoid returning millions of rows at once. Cursor-based pagination (GET /posts?after=cursor_xyz&limit=20) is more efficient than offset pagination for large datasets. The response includes a next_cursor or next URL for the client to fetch the next page.
Frequently Asked Questions
What is the difference between REST and GraphQL?
REST has multiple fixed endpoints; each returns a fixed shape. GraphQL has one endpoint where clients send a query describing exactly what fields they need. GraphQL solves over-fetching (REST returns more data than needed) and under-fetching (REST requires multiple round trips). REST is simpler and better understood; GraphQL adds client flexibility at the cost of server complexity.
When should I use POST vs PUT vs PATCH?
POST creates a new resource (the server assigns the ID). PUT replaces an entire resource (client specifies the ID and sends the full new state). PATCH partially updates a resource (send only the fields that changed). Use PUT when the client controls the resource ID; use PATCH when updating a subset of fields to avoid accidentally clearing fields the client didn't send.
How do I secure a REST API?
Always use HTTPS (never HTTP in production). Authenticate requests with JWT tokens or API keys in the Authorization header. Validate and sanitise all input server-side. Rate limit endpoints (especially auth endpoints) to prevent brute force. Use CORS to restrict which origins can call your API from browsers. Return minimal error detail to clients (don't expose stack traces).
What is the difference between 401 and 403?
401 Unauthorised means the request has no credentials or invalid credentials — the client should authenticate first. 403 Forbidden means the client is authenticated but not allowed to access this resource — re-authenticating won't help. Example: 401 if no token is sent; 403 if a regular user tries to access an admin endpoint.