68
API Basics
Web API Basics: Let Your Code Talk to External Systems
What you're probably confused about right now
"A 200 status code means I'm done, right?"
Not necessarily. You still need to validate the response body fields and business-level status.
One-line definition
An API is a data contract between systems -- exchanging requests and responses using methods and parameters.
Real-life analogy
A takeout window: you order from a set menu, and get results back in an agreed format.
Minimal working example
import requests
resp = requests.get("https://jsonplaceholder.typicode.com/posts/1", timeout=10)
print(resp.status_code)
print(resp.json())
Quick quiz (5 min)
- Call a user list API.
- Extract id/name/email.
- Save to a local JSON file.
Quiz answer guide & grading criteria
- Answer direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Take-home task
Write a fetch_json(url) wrapper with unified error handling and return structure.
Acceptance criteria
You can independently:
- Make GET/POST requests
- Handle status codes and exceptions
- Validate key response fields
Common errors & debugging steps (beginner edition)
- Can't read the error: start from the last line -- find the error type (
TypeError,NameError, etc.), then trace back to the line in your code. - Not sure about a variable's value: throw in a temporary
print(var, type(var))at key points to verify data looks right. - Changed code but nothing happened: make sure the file is saved, you're running the right file, and your terminal is in the correct venv.
Common misconceptions
- Misconception: no need to set a timeout.
- Reality: production code must always have timeouts.