RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Fredoline Eruo
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Python for AI — Zero to Useful
  6. /Ch. 18
Python for AI — Zero to Useful

18. Reading API Responses

Chapter 18 of 36 · 20 min
KEY INSIGHT

API responses are nested dictionaries. Use chained `.get()` calls with defaults to handle missing keys gracefully. List comprehensions extract fields from batched responses.

JSON Response Structure

AI APIs return structured JSON. Extract data carefully:

response = {
    "id": "chatcmpl-123",
    "model": "gpt-4",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "Hello! How can I help you?"
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 10,
        "completion_tokens": 12,
        "total_tokens": 22
    }
}

# Extract nested values
content = response["choices"][0]["message"]["content"]
usage = response["usage"]["total_tokens"]

Handling Missing Keys

# Safe extraction with defaults
def get_content(response):
    try:
        return response.get("choices", [{}])[0].get("message", {}).get("content", "")
    except (KeyError, IndexError, TypeError):
        return ""

# Or use .get() chaining
content = (
    response
    .get("choices", [{}])[0]
    .get("message", {})
    .get("content", "")
)

Batch Responses

AI APIs return lists of completions:

responses = [
    {"choices": [{"message": {"content": "Response 1"}}]},
    {"choices": [{"message": {"content": "Response 2"}}]},
    {"choices": [{"message": {"content": "Response 3"}}]}
]

contents = [r["choices"][0]["message"]["content"] for r in responses]

Pagination

Large results come in pages:

all_results = []
page_token = None

while True:
    params = {"limit": 100}
    if page_token:
        params["after"] = page_token
    
    response = requests.get(url, headers=headers, params=params).json()
    all_results.extend(response.get("data", []))
    
    page_token = response.get("next_cursor")
    if not page_token:
        break

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Create a mock API response with nested structure (like an AI completion). Extract the response content, token usage, and model name using safe extraction methods. Handle the case where any key might be missing. Continue to Part 2: Chapters 19-36


# PART 2: Intermediate Python for AI
← Chapter 17
Rate Limiting and Retries
Chapter 19 →
Object-Oriented Python