Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

5.3 Consuming APIs

How it works

An API returns structured data over the network, and both the request and the response can fail independently of your code being correct.

Check the response status before parsing, and handle the failure path explicitly.

Common error

Assuming a successful response. Network calls fail routinely and silently corrupt downstream logic.

Worked example

Python

response = {"status": 200, "body": {"items": ["A", "B"]}}
if response["status"] == 200:
    items = response["body"]["items"]
    print(len(items))

Output

2

This local response fixture separates processing from an actual network request. In a real client, check status, timeouts, and the expected response structure, and keep credentials out of source and logs.

Exercises

5.3.1 · Explain

Why should a client use a timeout and check the response status before processing an API body?

Show solution

A request may fail or stall, and an error body may not match the success format. Handle transport and application errors explicitly.

5.3.2 · Write code

Process a local response whose body contains values [3, 6], and print their sum only when status is 200.

Show solution

Check the status before using the success schema.

One valid solution

response = {"status": 200, "body": {"values": [3, 6]}}
if response["status"] == 200:
    print(sum(response["body"]["values"]))

Expected output

9
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic