When an API sends JSON, response.json() converts the response body from a string into a regular Python object. That makes returned data easier to inspect, index, and use in an application. section 5.3.3 section 11.1.1
Use the parsed value according to the shape of the JSON response:
- Treat a JSON array as a Python list; response.json()[0] selects its first element. section 5.3.3
- Treat a JSON object as a Python dictionary; access fields such as results or joke with dictionary keys. section 5.3.3 section 11.1.1
- Check the HTTP status before parsing, then provide a fallback when the request does not succeed. section 5.3.3
Reading a joke from an API
After a successful request, joke_obj = response.json()[0] retrieves the first returned object, and joke_obj['joke'] extracts its text for display. section 5.3.3
Listing 5.1 The jokes.py file
import requests
API_URL = "https://api.api-ninjas.com/v1/dadjokes"
def generate_joke(api_key):
headers = {"X-Api-Key": api_key}
response = requests.get(API_URL, headers=headers)
if response.status_code == requests.codes.ok:
joke_obj = response.json()[0]
return joke_obj['joke']
# Fall back to a default joke if the API fails
return f"Time flies like an arrow. Fruit flies like a banana."
See the complete requests example, including the status check, JSON parsing, extracted field, and fallback response. section 5.3.3
