Consume API data
Parse a JSON API response into dictionaries, lists, or scalar Python values.
Requests · Function
Response.json() decodes a response body as JSON and returns the corresponding Python object, such as a dictionary or list. It raises an exception when decoding fails.
Call this method on a Response to decode its body as JSON. The result is whichever Python value the JSON represents, such as a dictionary or list; decoding failures raise an exception.
Response.json(**kwargs) → Any| Name | Type | Description |
|---|---|---|
**kwargs | Any | Optional keyword arguments accepted by the JSON decoder. |
Any
import requests
response = requests.get("https://api.github.com/events")
response.raise_for_status()
events = response.json()
print(type(events).__name__)Fetches JSON from an endpoint, verifies the HTTP status, and converts the response body into a Python object.
Parse a JSON API response into dictionaries, lists, or scalar Python values.
Decode a response after checking its HTTP status.
Handle malformed or non-JSON bodies from an endpoint.
Response.json() parses the response body and returns the corresponding Python object. The returned value can be a dictionary, list, or another JSON-supported value.
Follow-up: What happens when the body is not valid JSON? The call raises an exception rather than returning a partially decoded value.
It is a method, so it must be invoked with parentheses. The documentation specifically distinguishes the callable form from the older property-style form.
Follow-up: How would you avoid treating an error page as JSON? Check the HTTP status first, then call json() and handle decoding errors.
The method decodes the response body; it does not itself establish that the HTTP request succeeded. Status handling should therefore be performed separately when success is required.
Follow-up: What should a client do before decoding an API response? Raise for an unsuccessful status or otherwise inspect the status code, then decode the body.
requests.getrequests.postrequests.Responserequests.exceptions.JSONDecodeError