HTTP & RESTful APIs
Chapter 1: The Universal Language - How Apps Talk
If you order a pizza in Italy, you need to speak Italian (or point at pictures). If your phone wants to talk to a server in Virginia, it needs a language too.
That language is HTTP (HyperText Transfer Protocol).
🍽️ Real World: The RestaurantClient (You): "I would like one burger, please." (Request)
Server (Kitchen): "Here is your burger." (Response)
This simple exchange is the foundation of the entire internet.
Chapter 2: Anatomy of a Request
Every time you click a button, your browser sends a message. It looks like this:
POST /orders HTTP/1.1
Host: api.pizza.com
Authorization: Bearer my-secret-token
Content-Type: application/json
{
"item": "Pepperoni",
"size": "Large"
}
2.1 The Method (The Verb)
What do you want to DO?
- GET: "Give me data." (Read-only. Safe to call 100 times).
- POST: "Create new data." (Buying a ticket).
- PUT: "Replace this data completely." (Update profile).
- PATCH: "Change just one field." (Update email only).
- DELETE: "Remove this." (Cancel order).
2.2 The Headers (The Metadata)
Information ABOUT the message.
Authorization: Who are you?Content-Type: What language am I speaking? (usuallyapplication/json).User-Agent: Are you a browser, a phone, or a python script?
2.3 The Body (The Payload)
The actual details (like the JSON above). GET requests usually don't have a body.
Chapter 3: Anatomy of a Response
The server replies:
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": 55,
"status": "Cooking",
"eta": "20 mins"
}
3.1 Status Codes (The Scorecard)
A 3-digit number that tells you if it worked.
| Range | Examples | Meaning |
|---|---|---|
| 2xx (Success) | 200 OK 201 Created 204 No Content |
"It worked!" "I built it." "Done (but I have nothing to show you)." |
| 3xx (Redirection) | 301 Moved Permanently 304 Not Modified |
"It's over there now." "You already have the latest version (Cache)." |
| 4xx (Client Error) | 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 429 Too Many Requests |
"You typed it wrong." "Who are you?" "I know you, but you can't come in." "It doesn't exist." "Slow down!" |
| 5xx (Server Error) | 500 Internal Server Error 503 Service Unavailable |
"Our code crashed." "We are overloaded/down for maintenance." |
Chapter 4: RESTful Design - Organizing Your URLs
REST (Representational State Transfer) is a style guide for URLs. Think of your API as a filing cabinet.
4.1 Use Nouns, Not Verbs
- ❌ Bad:
/getAllUsers,/createNewUser,/deleteUser - âś… Good:
GET /users,POST /users,DELETE /users/123
Why? Because the Verb (GET/POST) already tells us the action. The URL should tell us the Thing (Resource).
4.2 Hierarchy and Nesting
If data belongs to other data, nest it.
GET /users/5/orders- Get orders belonging to user 5.GET /users/5/orders/99- Get specific order #99 for user 5.
Chapter 5: Idempotency - The "Double Charge" Problem
This is crucial for payments.
đź’ł Real World: The Freezing ScreenYou click "Pay Now". The screen freezes. Did it work? You click "Pay Now" again.
- Bad API: Charges you twice.
- Good API (Idempotent): Sees the second request, realizes it's a repeat, and does nothing (but returns "Success").
How to do it:
- Client generates a unique ID (GUID) representing this transaction.
- Client sends header:
Idempotency-Key: abc-123. - Server checks DB: "Have I seen
abc-123before?"- Yes: Return previous result immediately.
- No: Process payment, save Key, return result.
Chapter 6: Pagination - Don't Download the Internet
If you have 1 million users, GET /users will crash your server and the user's browser.
6.1 Offset Pagination (The Book Page style)
GET /users?page=3&pageSize=10
Pros: Human readable ("Jump to Page 5").
Cons: Unstable. If a new user joins while you are reading Page 2, Page 3 might show you a duplicate of someone you just saw.
6.2 Cursor Pagination (The Infinite Scroll style)
GET /users?afterId=1055&limit=10
Pros: Extremely clear. "Give me 10 users starting after User #1055". Handles new data perfectly.
Cons: Can't jump to "Page 500" arbitrarily.
Chapter 7: Summary Checklist
Before you launch your API:
- [ ] Use Plural Nouns:
/usersnot/user. - [ ] Return Standard Status Codes: Don't return
200 OKfor an error. - [ ] Use ISO-8601 Dates:
"2023-12-25T10:00:00Z"(UTC). Never use local time formats. - [ ] Implement Rate Limiting: Don't let one script killer your server (429).
- [ ] Validate Inputs: Return
400 Bad Requestwith a clear message if data is wrong.
Quick Review
HTTP is a stateless request/response protocol for client-server communication, and REST is a resource-oriented design style on top of HTTP, allowing APIs to remain predictable and scalable.
âś… Requests and responses
- Method: the action (GET, POST, PUT, PATCH, DELETE).
- Headers: metadata (auth, content type, caching, tracing).
- Body: the data you send (usually JSON).
- Status code: the outcome category (2xx ok, 4xx client issue, 5xx server issue).
âś… REST URL design
- Resources are nouns:
/users,/orders. - Hierarchy shows ownership:
/users/5/orders. - HTTP verbs carry meaning: GET reads, POST creates, PUT replaces, PATCH updates, DELETE removes.
âś… Reliability patterns
- Idempotency: a repeated request shouldn’t cause repeated side effects (use an idempotency key for risky operations).
- Pagination: never return “everything”; offset is simple, cursor is stable at scale.
- Input validation + rate limits: protect your server and give clear errors.