Calling APIs from Python
Why this matters
This is the lesson where your code starts talking to the outside world. Calling an LLM, pulling campaign data, posting results to Slack, giving an agent its tools: each one is a few lines of requests. The habits here are to check the status, read the error, and set a time limit. They're what separate a script that works once from one you can leave running.
- Send GET and POST requests with the requests library
- Pass query parameters and JSON bodies without building strings by hand
- Read status codes and JSON responses in code
- Handle the three ways an API call fails: error status, no connection, too slow
The requests library
Python can make HTTP requests with its standard library. But almost everyone uses the requests package, because it's far simpler. Think of it as a courier: you hand it an address and a package, and it comes back with the reply. On your own machine you'd install it with pip install requests. In the academy it's already available.
import requests response = requests.get("https://api.gradient.test/v1/campaigns") print(response.status_code) print(response.headers["content-type"]) data = response.json() print(data["count"], "campaigns")
requests.get(url) sends a GET request and gives back a Response object. The parts you'll use most:
| Attribute | What it holds |
|---|---|
response.status_code | the status code, such as 200 |
response.ok | True for any status below 400 |
response.json() | the body parsed from JSON into Python dicts and lists |
response.text | the body as a plain string |
response.headers | the response headers, like a dictionary |
.json() does the json.loads step for you. If the body isn't JSON, such as an HTML error page, it raises an error. That's why it's worth checking the status first.