Handling API Responses and Errors
Parsing JSON responses, error codes, and exception handling patterns.
The Response Object
Every requests call returns a Response object. It contains everything the server sent back: the status code, headers, and body. Before processing the body, always inspect the status code — a response with a 500 status still has a body, but it won't contain the data you wanted.
import requests
response = requests.get('https://api.example.com/data')
# Key attributes of the response
print(response.status_code) # e.g. 200
print(response.headers) # dict of response headers
print(response.headers.get('Content-Type')) # 'application/json'
print(response.text) # raw response body as string
print(response.content) # raw bytesParsing JSON with response.json()
Call response.json() to automatically parse the response body as JSON into a Python dict or list. This is equivalent to json.loads(response.text), but also validates that the Content-Type is appropriate.
Only call .json() when you know the response is actually JSON — check the Content-Type header first.
import requests
response = requests.get(
'https://api.example.com/users/42',
headers={'Authorization': 'Bearer YOUR_KEY'}
)
# Parse JSON body
user = response.json()
# Access fields safely with .get()
name = user.get('name', 'Unknown')
email = user.get('email', '')
roles = user.get('roles', [])
print(f'User: {name} ({email})')
print(f'Roles: {roles}')All lessons in this course
- REST API Fundamentals for Agent Developers
- Authentication: API Keys and OAuth
- Handling API Responses and Errors
- Rate Limiting and Retry Logic