Definition
An API lets programs talk to each other, usually over HTTP. A client sends a request (GET to read, POST to send) to a URL, and receives a response with a status code and usually JSON data. requests is the most popular Python library for this.
In simple words
A restaurant has a menu and a waiter. You don't go into the kitchen. You order from the menu (API), the waiter (HTTP) takes it, and food (data) comes back.
Why it matters
Every LLM API, payment system and weather feed works this way. Calling an AI model from your app is just an HTTP POST.
How it works
| Status | Means |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Your request is wrong |
| 401 / 403 | Not logged in / not allowed |
| 404 | Not found |
| 429 | Too many requests: slow down |
| 500 | The server failed |
import requests
response = requests.get(
"https://api.example.com/users",
params={"city": "Pune"},
headers={"Authorization": f"Bearer {api_key}"},
timeout=10, # always set a timeout
)
response.raise_for_status() # error on 4xx or 5xx
data = response.json()
requests.post(url, json={"name": "Riya"}, timeout=10)In code
A real API call needs a network, so here we handle a saved response, as you would handle a real one.
import json
raw = '{"users": [{"name": "Riya", "city": "Pune"}, {"name": "Aman", "city": "Delhi"}], "total": 2}'
status_code = 200
if status_code == 200:
data = json.loads(raw)
for user in data["users"]:
print(user["name"], "from", user["city"])
print("Total:", data["total"])
else:
print("Request failed:", status_code)
body = json.dumps({"prompt": "Hello", "max_tokens": 50})
print("What a POST might send:", body)Output
Riya from Pune
Aman from Delhi
Total: 2
What a POST might send: {"prompt": "Hello", "max_tokens": 50}Common mistakes
- Leaving out timeout, so a stuck server hangs your program for ever.
- Putting API keys in code. Read them from the environment.
- Ignoring status codes and assuming success.
Check yourself
Summary
- APIs let programs talk over HTTP.
- GET reads and POST sends, usually with JSON.
- Always set a timeout and check the status.
Finished reading?
Sources: Requests documentation