Calling web APIs: HTTP, JSON, status codes and errors
Python for AI Apps · 10 questions
Short notes
Key idea
Most AI services are web APIs: you send an HTTP request with JSON and get JSON back. Know the methods, the status codes, and how to handle failures and timeouts.
Syntax
import httpx
r = httpx.post(
"https://api.example.com/v1/items",
headers={"Authorization": f"Bearer {key}"},
json={"name": "pen"},
timeout=10,
)
r.raise_for_status()
data = r.json()
- Methods: GET (read), POST (create / send), PUT/PATCH (update), DELETE.
- Status codes: 200 OK, 201 created; 400 bad request, 401/403 auth, 404 not found, 429 too many requests; 500/503 server problems.
Example
A weather API call with params={"city": "Chennai"} returns JSON. If it returns 429, wait and retry; if 401, the key is wrong and retrying won't help.
Traps
- No timeout means a call can hang forever.
- Not checking the status:
r.json()on an error page fails or gives an error body. - Keys in URLs end up in logs; send them in headers.
- Retry only temporary errors (429, 5xx), with backoff.
Want the full lesson with step-by-step examples, a project and a certificate? Python for AI Apps course, ₹180 →
- Question 1easy
You send a customer's message to an LLM API to get a reply. Which HTTP method fits?
- Question 2easy
What does this print?
from urllib.parse import urlencode print(urlencode({"city": "Chennai", "days": 3})) - Question 3easy
An API returns 404. Whose problem is it, usually?
- Question 4medium
What does this print?
def what_to_do(status): if 200 <= status < 300: return "use" if status == 429 or status >= 500: return "retry" return "fix" print(what_to_do(201), what_to_do(401), what_to_do(502)) - Question 5medium
Why call response.raise_for_status() before response.json()?
Calling web APIs: HTTP, JSON, status codes and errors
Calling web APIs: HTTP, JSON, status codes and errors
Calling web APIs: HTTP, JSON, status codes and errors
Calling web APIs: HTTP, JSON, status codes and errors
Calling web APIs: HTTP, JSON, status codes and errors
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.