Libraries · 22 min

Install packages and read an HTTP API

Use a virtual environment, install Requests, and process JSON responses.

Jump to the automation lab

A package groups importable modules. A regular local package has a directory such as catalog/ with an __init__.py file. PyPI is the package index used by pip. A virtual environment gives a project its own interpreter and installed packages.

A GET request asks an endpoint for data. Specify a timeout and call raise_for_status() before reading the body. An HTTP 2xx status represents success, 4xx identifies a client-side error, and 5xx identifies a server-side error.

response.json() parses a JSON body into Python values. A successful HTTP status still leaves you responsible for validating the shape of the data. The browser exercise uses saved response text so the result stays reproducible.

Follow the example

A sample successful response contains a list of books.

Worked examples

Make a live request from your terminal

Create the environment and use its Python to install Requests and fetch a public repository. These commands use the macOS and Linux path. On Windows, use .venv\Scripts\python.exe in place of .venv/bin/python.

repo.py
import requests


def repository_name(owner, repo):
    url = f"https://api.github.com/repos/{owner}/{repo}"
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    return response.json()["full_name"]


if __name__ == "__main__":
    print(repository_name("python", "cpython"))
Terminal
python -m venv .venv
.venv/bin/python -m pip install requests
.venv/bin/python repo.py

Import from your own package

Save each block at the shown path. Run the last command from the directory containing catalog/ and report.py.

catalog/__init__.py
# Marks catalog as a regular package.
catalog/display.py
def label(title):
    return title.strip().title()
report.py
from catalog.display import label

print(label("  dawn valley  "))
Terminal
python report.py

Run the example and practice

Return only the titles of books with at least minimum_pages pages. Keep the sample threshold at 200.

Target output

['Rain']
Show a hint

Add an if condition to the list comprehension. Include books exactly at the threshold.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import json

response_text = '{"books":[{"title":"Dawn","pages":180},{"title":"Rain","pages":220}]}'

def titles_at_least(payload, minimum_pages):
    return [
        book["title"] for book in payload["books"]
        if book["pages"] >= minimum_pages
    ]

print(titles_at_least(json.loads(response_text), 200))

Automation lab

Collect workshop titles from a saved webpage

Use Beautiful Soup to read sample HTML. A saved page lets you repeat the example even if the live page changes.

Output

Ready

Run the example to see the output here.

Add another workshop and an unrelated heading. Which titles are collected?

Further reading in Automate the Boring Stuff with Python by Al Sweigart