API basics with requests
An API lets programs exchange data. Python's requests library sends HTTP requests to web APIs and reads their responses.
This lesson uses JSONPlaceholder, a public API with pretend data. You need no account or API key. Start with Dictionaries and JSON.
Run the examples
Use the Run buttons below to run Python in your browser. The first run downloads requests and its dependencies; later blocks reuse them while the Python runner stays open. Other libraries are loaded only when a block imports them.
To run the same examples on your own computer, install requests in your terminal:
python -m pip install requests
The browser examples need internet access. Browser security rules also apply: an API must allow cross-origin requests (CORS).
Send a GET request
A GET request asks a server for data. An endpoint is an API address, such as /todos/1 for task 1.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/todos/1", timeout=10)
response.raise_for_status()
print(response.status_code)
print(response.text)
On success, this prints 200, then the response body as JSON text.
The status code describes the result: 200 means success; 404 means not found. raise_for_status() raises an exception for HTTP errors such as 404 or 500.
timeout=10 limits connection and read waits to 10 seconds each. It is not a total download deadline. In the browser, timeout handling is controlled by browser networking and may differ; the Run button also has its own execution time limit.
Read JSON as Python data
response.json() converts JSON into Python values. This endpoint returns an object, which becomes a dictionary.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/todos/1", timeout=10)
response.raise_for_status()
task = response.json()
print(task["title"])
print(task["completed"])
This prints delectus aut autem, then False. JSON's false becomes Python's False.
Filter with query parameters
Query parameters add options to a URL. Pass a dictionary to params to request tasks belonging to user 1.
import requests
response = requests.get(
"https://jsonplaceholder.typicode.com/todos",
params={"userId": 1},
timeout=10,
)
response.raise_for_status()
tasks = response.json()
print(response.url)
print(tasks[0]["title"])
This prints a URL ending in /todos?userId=1, then delectus aut autem.
This endpoint returns a JSON array, which becomes a list of dictionaries. tasks[0] selects the first dictionary; ["title"] reads its title.
Handle a failed request
A server can be unavailable or return an error. Catch RequestException to display a message when that happens.
import requests
try:
response = requests.get("https://jsonplaceholder.typicode.com/todos/1", timeout=10)
response.raise_for_status()
task = response.json()
except requests.exceptions.RequestException:
print("Could not read the task. Try again later.")
else:
print(task["title"])
This prints the title on success, or the message on a request failure.
Note: Not every API returns JSON. response.json() can fail on invalid JSON; the handler above catches that too. See the Requests quickstart for details.
See also: JSON, Dictionaries, try and except.
Your turn
This fixed sample represents data returned by response.json() and runs without internet access. Add two lines: print the task's title, then its completion value.
task = {"userId": 1, "id": 1, "title": "delectus aut autem", "completed": False}
# add two lines: print the title, then the completed value
Expected output
delectus aut autem
False