Chapter 3: Your First API Call
1. Your first API call
In the next few minutes, you're going to fetch live data from the internet with Python. Not a simulation, not a pre-baked tutorial dataset, but real information from actual servers, the same way Instagram loads your feed or your weather app shows today's forecast. By the end of this chapter you'll have sent dozens of requests and built a small program that combines two real APIs end-to-end.
This is the moment where everything starts to click. You've installed Python, set up your environment, and learned the core ideas. Now you'll see APIs in action, in real time. Every time you open a weather app, scroll social media, or check your bank balance, your device is quietly making API calls. In this chapter, you join the developers who build those conversations on purpose.
What this chapter does
We'll start with the smallest possible request, one line of Python that connects to a real server, and work up from there. Here's what that looks like:
- How to send a GET request with the
requestslibrary - What a
Responseobject contains: status, headers, body - How JSON maps onto Python dictionaries and lists
- Why every request needs a
timeout(and what happens without one) - HTTP status codes: the 200s, the 400s, and the 500s
- Handling failures with
try/exceptandraise_for_status() - Query parameters and the
paramsargument
first_request.py, four lines that fetch a random cat fact from a real APIpeek_response.pyandparse_cat_fact.py, take the same request and walk through what's inside the Response objecthttpbin_get.py, inspects what your HTTP client is really sendingwith_timeout.py, demonstrates how a timeout protects you from a slow serverinspect_response.py, builds up a diagnostic script that surfaces status, headers, and metadatahandle_errors.pyandtest_status_codes.py, exercise thetry/exceptsafety-net pattern against real failure codesquery_params.py, sends customised requests with theparamsargumentcat_facts_and_jokes.py, the complete mini project that combines two APIs with timeouts and basic error handling
Every API call in this book follows the same rhythm: ask, wait, inspect, use. You send a request, wait for a response, check that it succeeded, then use the data. In Chapter 4 you'll meet a tighter version of this rhythm called Make → Check → Extract, the same shape, three steps instead of four. The tools and APIs change from chapter to chapter; the shape of the work doesn't.
Next, we'll make the first request. Four lines of Python, one live server, one real response. If you've got your environment set up from Chapter 2, you're ready to go.