When working with APIs in Python, you'll often get JSON data back in the response. The requests library makes it easy to parse this JSON and access the data you need.
Use response.json()
The simplest way is to call the
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
print(data['key1'])
This automatically parses the JSON and returns a Python dict that you can access just like any other dict.
Handling invalid JSON
If the API returns invalid JSON,
try:
data = response.json()
except JSONDecodeError:
print('Response was not valid JSON')
Accessing response status codes
It's good practice to check the status code before trying to parse the response. For example:
if response.status_code == 200:
data = response.json()
else:
print(f'Error with status code {response.status_code}')
This makes sure you only try to parse valid responses.
Response Content Type
Also check that the
In Summary
Parsing JSON from APIs is smooth with Python requests! Proper error handling avoids surprises.