JSON (JavaScript Object Notation) is a text-based format for exchanging structured data. It represents information with objects, arrays, and name-value pairs, making API responses readable and practical to process. section 5.3.1 section 5.3.3
When an API returns JSON, Python's requests library can parse the response with response.json(). The resulting Python object can then be handled like an ordinary list or dictionary. section 5.3.3
A typical JSON API workflow is:
- Send an HTTP request to an API endpoint, optionally providing URL parameters, request data, headers, or an API key. section 5.3.1
- Check the response status code before processing the result. section 5.3.3
- Parse the JSON body, select the needed list element or dictionary key, and use the extracted value in the application. section 5.3.3
- Return a fallback value when the API request fails, so the application can respond gracefully. section 5.3.3
Reading a joke from an API response
A response such as [{"joke": "I want to name my puppies Rolex and Timex so I can have watch dogs."}] becomes a Python list after response.json(). Select its first dictionary with response.json()[0], then retrieve the text with joke_obj['joke']. section 5.3.3
{
"high_temp": 72,
"low_temp": 60,
"forecast_text": "Nice and sunny, a good day for the park"
}
Inspect a compact JSON object containing numeric values and text fields. section 5.3.1
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."
Inspect a complete Python function that requests JSON, checks success, extracts a value, and supplies a fallback. section 5.3.3


































