← Python lessons

Inspecting API responses

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

An unfamiliar API response can contain hundreds of fields and records. Inspect one layer at a time to discover the path to the values you need. Start with API basics with requests and Nested Dictionaries and Lists.

Fetch once, then explore

This live example needs internet access. Store the decoded data so you can inspect different parts without making more requests during the same run.

import jsonimport requestsresponse = requests.get("https://pokeapi.co/api/v2/pokemon/pikachu", timeout=10)response.raise_for_status()pokemon = response.json()preview = json.dumps(pokemon, indent=2)print("JSON preview (first 4,000 characters):")print(preview[:4000])if len(preview) > 4000:    print("[Preview cut here; pokemon still contains the complete response.]")print("Top-level keys:", list(pokemon.keys()))

The preview makes the nesting visible. It may end halfway through a value and is not a complete JSON document. Do not try to parse the preview: pokemon already holds the complete decoded response. Printing a whole large response can exceed the console's output limit.

Use json.dumps(value, indent=2) to format a smaller branch completely. response.json() decodes JSON; your dictionary and list lookups select values from the decoded data.

Identify the outer structure

These remaining examples use fixed data and run offline, independently of the live example. First decide whether the response is a dictionary or a list. A dictionary has named keys; a list has numbered positions.

data = {"total": 2, "results": [{"name": "Ada", "score": 12}, {"name": "Lin", "score": None}]}print(type(data).__name__)print(list(data.keys()))print(type(data["results"]).__name__)print(len(data["results"]))

This prints dict, ['total', 'results'], list, then 2. The result list is inside the outer dictionary; the names are not top-level fields. If the endpoint returns a list at the root, inspect its length and a sample item instead of calling .keys().

Inspect one complete record

Check that a list has an item before reading index 0. Formatted output helps distinguish a list from a dictionary nested inside it.

import jsondata = {"results": [{"name": "Ada", "profile": {"city": "Hobart"}}, {"name": "Lin"}]}records = data["results"]if records:    print(json.dumps(records[0], indent=2))    print(records[0]["profile"]["city"])else:    print("No records to inspect")

Follow the path left to right: results selects a list, 0 selects a dictionary, profile selects another dictionary, and city selects a string. The second record has no profile; inspecting one record does not establish that every record has identical fields.

Show keys and types instead of values

A top-level type summary is useful when the response is too large to read. .items() gives each dictionary key together with its value; type(value).__name__ gives the Python type's name.

data = {"name": "Ada", "active": True, "scores": [12, 18], "profile": {}, "extra": None}for key, value in data.items():    print(f"{key}: {type(value).__name__}")

The lines identify str, bool, list, dict and NoneType. These are Python type names: JSON objects become dictionaries, arrays become lists, and null becomes None.

The API course supplies describe_structure for nested inspection. It prints no field values: it walks dictionaries and samples item 0 of non-empty lists, with depth and line limits. A branch might look like this:

response: dict
  results: list
    [sample 0]: dict
      name: str
      score: int

Treat this as an observed structure, not the API's complete schema. Empty lists have unknown item types. Other records can omit keys, contain None, or contain different types. Compare several records and consult the API documentation. Documentation also explains meanings and units that a type summary cannot reveal.

Move from investigation to a result

Use inspection prints while working, then remove them from a function whose contract is to return data. In the course editor, keep exploratory code in the area below the marked grading boundary; Submit excludes that area. Before applying a path to every record, decide how the task should handle missing keys, None and empty lists.

Your turn

This response is fixed and works offline. Print the type of results, then print the keys and Python types in its first record. Print types, not the values themselves.

🎯 Goal — make it print exactly:
list
name: str
score: int
extra: NoneType
data = {"results": [{"name": "Ada", "score": 12, "extra": None}]}# Inspect results, then loop over the first record's items.