Working with APIs in Python
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 217 wordsLearn how to interact with APIs in Python, including making requests, handling JSON data, and authenticating with APIs.
APIs (Application Programming Interfaces) allow you to interact with web services programmatically. This guide covers making requests, handling JSON data, and authenticating with APIs in Python.
import requests
url = "https://api.example.com/data"
response = requests.get(url)
print(response.json())
Handling errors in API requests.
if response.status_code == 200:
print(response.json())
else:
print(f"Error: {response.status_code}")
data = response.json()
print(data["key"])
Parsing nested JSON data.
nested_data = data["nested_key"]
for item in nested_data:
print(item["sub_key"])
api_key = "your_api_key"
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get(url, headers=headers)
print(response.json())
API key authentication example.
api_key = "your_api_key"
url = "https://api.example.com/data"
response = requests.get(url, headers={"Authorization": f"Bearer {api_key}"})
print(response.json())
Use libraries like requests-oauthlib
for OAuth authentication.
pip install requests-oauthlib
from requests_oauthlib import OAuth1Session
client_key = 'your_client_key'
client_secret = 'your_client_secret'
oauth = OAuth1Session(client_key, client_secret)
response = oauth.get(url)
print(response.json())
if response.status_code == 200:
data = response.json()
else:
print(f"Error: {response.status_code}")
Handling common error codes.
if response.status_code == 404:
print("Not Found")
elif response.status_code == 500:
print("Server Error")
else:
print(f"Unexpected Error: {response.status_code}")
Interacting with APIs is a crucial skill for modern programming. Practice making API requests, handling JSON data, and authenticating with various methods to effectively use APIs in your Python projects.