liveBook · Manning

Response.json()

As explained in Build Python Web Apps with Streamlit

response.json is a requests response method that parses a JSON response body into a Python object.

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

How Build Python Web Apps with Streamlit covers it

How deep it goes
Explains conversion from response text to Python lists and dictionaries, then demonstrates indexing and key access.
Examples
Demonstrates dad-joke data and TMDB movie-search results, including arrays, dictionaries, and extracted fields.
What it assumes
Assumes basic Python and requests usage while explaining JSON structure and parsing from the response text.
What you can do after
Apply it via the requests library to extract usable Python data from successful JSON API responses.
How it connects
Connects HTTP responses, JSON, Python objects, API requests, status codes, lists, and dictionaries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.