PythonMastery

How do I call an API in Python?

requests.get(url, timeout=10), then raise_for_status() and .json(). Always set a timeout: without one, a server that stops answering hangs your program.

Install requests once (pip install requests), then a call is three lines that matter: make the request, check it worked, read the JSON.

python · run on your machine
import requests

response = requests.get(
    "https://api.github.com/repos/python/cpython",
    timeout=10,
)
response.raise_for_status()          # stop here on 404, 500 and friends
repo = response.json()               # the body, parsed into a dict

print(repo["full_name"], "has", repo["stargazers_count"], "stars")

That block is meant for your own machine (new to running Python there? start with the terminal). In a browser, a page can only call servers that allow it. GitHub's API does, so this one also works in the online editor, but many others don't. Everything after response.json() is ordinary Python, and you can run that part. Here is the same handling on a dict shaped like GitHub's reply (the numbers are made up):

python
data = {
    "full_name": "python/cpython",
    "stargazers_count": 68000,
    "topics": ["python", "interpreter"],
    "license": {"name": "Other"},
}

print(data["full_name"], "has", data["stargazers_count"], "stars")
print("topics:", ", ".join(data.get("topics", [])))
print("licence:", data.get("license", {}).get("name", "none"))
output
python/cpython has 68000 stars
topics: python, interpreter
licence: Other

The chained .get(..., {}) is worth copying: real APIs leave fields out, and one missing key shouldn't crash the whole run.

The three lines people skip

python · run on your machine
import requests

response = requests.get(
    "https://api.github.com/search/repositories",
    params={"q": "web scraping language:python", "per_page": 5},
    timeout=10,
)
response.raise_for_status()
for repo in response.json()["items"]:
    print(repo["full_name"])

Sending data

json= turns a dict into a JSON body and sets the header for you. Keep keys out of your code and read them from the environment:

python · run on your machine
import os
import requests

response = requests.post(
    "https://api.example.com/v1/orders",
    json={"product": "Notebook", "quantity": 2},
    headers={"Authorization": f"Bearer {os.environ['SHOP_API_KEY']}"},
    timeout=10,
)
response.raise_for_status()
print(response.json()["id"])

The APIs lesson continues from here: pagination, retries with back-off, and rate limits.

Go deeper: Consuming REST APIs, TimeoutError / requests.exceptions.ReadTimeout, json.JSONDecodeError: Expecting value, The Terminal for Python Developers

More short answers

all questions