What is an API? REST Architecture Explained
Whenever you check live cricket scores, query weather forecasts, or ask ChatGPT a question in your Python app, you are talking to an API (Application Programming Interface).
An API is a messenger that allows two independent software programs to talk to each other over the internet.
1. The Real-World Metaphor: The Restaurant Waiter
Think of a restaurant:
- You (The Client / Python App): You sit at the table with the menu.
- The Kitchen (The Server / Database): Where the food is prepared and stored.
- The Waiter (The API): You give your food order (HTTP Request) to the waiter. The waiter walks to the kitchen, brings your food back, and delivers it to your table (HTTP Response).
+------------------+ HTTP Request (GET /weather) +------------------+
| Python Program | ──────────────────────────────────────────> | Cloud Server |
| (The Client) | <────────────────────────────────────────── | (Weather DB) |
+------------------+ HTTP Response (JSON: 28°C) +------------------+
2. Anatomy of an HTTP Request
When your Python code talks to an API server, it sends four pieces of information:
- Endpoint (URL): Where the resource lives (e.g.
https://api.github.com/users/octocat). - HTTP Method (Action verb): What action you want the server to perform.
- Headers: Metadata (e.g.
Content-Type: application/jsonor authentication tokens). - Body (Payload): Data sent along with POST/PUT requests (e.g. login credentials).
3. The Core HTTP Action Verbs
| Method | What It Does | Real-World CRUD Equivalent |
|---|---|---|
GET | Fetch data from the server (Read only) | Read |
POST | Create a brand new resource on the server | Create |
PUT / PATCH | Update or modify existing records | Update |
DELETE | Remove a record from the database | Delete |
4. Understanding HTTP Status Codes
When an API answers back, it includes a 3-digit numerical status code indicating whether the request succeeded:
2xx: Success
• 200 OK: Request succeeded.
• 201 Created: New record saved.
3xx: Redirection
• 301 Moved Permanently: Resource has a new URL.
4xx: Client Mistakes
• 400 Bad Request: Invalid JSON syntax.
• 401 Unauthorized: Missing or invalid API key.
• 404 Not Found: Endpoint URL does not exist.
5xx: Server Crashes
• 500 Internal Server Error: Bug inside cloud server code.
• 503 Service Unavailable: Server overloaded.
Quick Summary
- REST API: Client-server communication protocol enabling programs to exchange JSON over HTTP/HTTPS.
- HTTP Methods:
GET(fetch data),POST(create new resource),PUT/PATCH(update),DELETE(remove). - Status Code Families:
2xx(Success),3xx(Redirection),4xx(Client Errors like 401 Unauthorized / 404 Not Found),5xx(Server Errors).
What's Next?
Let's learn how to make live HTTP GET requests, query parameters, and parse JSON using Python's requests library in Fetching Data with GET Requests!