Lesson 27 of 34

Requests, HTTP & APIs

Most useful programs eventually talk to another service. Requests makes HTTP readable while still exposing the timeouts, headers, , and sessions that reliable clients need.

Bash
python -m pip install requests
Python
import requests

url = "https://api.github.com/repos/python/cpython"
headers = {"Accept": "application/vnd.github+json"}

try:
    response = requests.get(url, headers=headers, timeout=(3.05, 15))
    response.raise_for_status()
    repository = response.json()
except requests.Timeout:
    print("The service took too long to respond")
except requests.HTTPError as error:
    print(f"HTTP failure: {error.response.status_code}")
except requests.RequestException as error:
    print(f"Network failure: {error}")
else:
    print(repository["full_name"], repository["stargazers_count"])

# Query parameters are encoded safely for you
requests.get(
    "https://api.example.com/search",
    params={"q": "python tips", "page": 2},
    timeout=10,
)
Python
import os
import requests

# A Session reuses connections and shared settings
with requests.Session() as session:
    session.headers.update({
        "Authorization": f"Bearer {os.environ['API_TOKEN']}",
        "User-Agent": "inventory-tool/1.0",
    })
    response = session.post(
        "https://api.example.com/items",
        json={"name": "keyboard", "quantity": 3},
        timeout=15,
    )
    response.raise_for_status()
    created = response.json()

# Stream large downloads instead of loading them all into memory
with requests.get(download_url, stream=True, timeout=30) as response:
    response.raise_for_status()
    with open("download.bin", "wb") as output:
        for chunk in response.iter_content(chunk_size=64 * 1024):
            output.write(chunk)
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.