Consuming JSON APIs in Python (with requests and json Modules)
Introduction
APIs often return data in JSON format, a lightweight and human-readable data interchange format. Python's requests and json libraries make it easy to consume RESTful JSON APIs.
Required Modules
Install requests (if not installed):
pip install requests
Then import:
import requests
import json
1. Making a GET Request to a JSON API
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print("Status Code:", response.status_code)
print("JSON Response:", response.json())
Output:
Status Code: 200 JSON Response: {'userId': 1, 'id': 1, 'title': '...', 'body': '...'}
2. Accessing JSON Fields from Response
data = response.json()
print("Title:", data['title'])
print("Body:", data['body'])
3. Consuming a JSON API that Returns an Array
response = requests.get("https://jsonplaceholder.typicode.com/posts")
data = response.json()
# Print first 3 posts
for post in data[:3]:
print(post['id'], post['title'])
Output:
1 sunt aut facere repellat 2 qui est esse 3 ea molestias quasi
4. POST Data to a JSON API
url = "https://jsonplaceholder.typicode.com/posts"
payload = {
"title": "Python API Demo",
"body": "This is from Python!",
"userId": 1
}
response = requests.post(url, json=payload)
print("Status Code:", response.status_code)
print("Response JSON:", response.json())
Output:
{ 'title': 'Python API Demo', 'body': 'This is from Python!', 'userId': 1, 'id': 101 }
5. Send Headers with API Request
headers = {'Content-Type': 'application/json'}
response = requests.get("https://jsonplaceholder.typicode.com/posts", headers=headers)
print(response.status_code)
6. Handle API Errors Gracefully
response = requests.get("https://jsonplaceholder.typicode.com/invalid-url")
if response.status_code == 404:
print("API endpoint not found.")
else:
print("Success!")
7. Save JSON Response to a File
with open('data.json', 'w') as f:
json.dump(response.json(), f, indent=4)