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:

What you'll learn
  • How to send a GET request with the requests library
  • What a Response object 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/except and raise_for_status()
  • Query parameters and the params argument
What you'll build
  • first_request.py, four lines that fetch a random cat fact from a real API
  • peek_response.py and parse_cat_fact.py, take the same request and walk through what's inside the Response object
  • httpbin_get.py, inspects what your HTTP client is really sending
  • with_timeout.py, demonstrates how a timeout protects you from a slow server
  • inspect_response.py, builds up a diagnostic script that surfaces status, headers, and metadata
  • handle_errors.py and test_status_codes.py, exercise the try/except safety-net pattern against real failure codes
  • query_params.py, sends customised requests with the params argument
  • cat_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.