Search This Blog

Automating API Interactions with Python

 

Automating API Interactions with Python

APIs (Application Programming Interfaces) allow applications to communicate and exchange data. Python provides powerful libraries like requests and httpx for automating API interactions, such as retrieving data, submitting forms, and integrating with third-party services.


Installing Required Libraries

To work with APIs, install the requests and httpx libraries:

pip install requests httpx
  • requests: Simplifies HTTP requests (GET, POST, PUT, DELETE).
  • httpx: Supports asynchronous API requests for faster execution.

Understanding API Requests and Responses

Common HTTP Methods

  • GET – Retrieve data from an API.
  • POST – Send data to an API.
  • PUT – Update existing data.
  • DELETE – Remove data from an API.

Making a Basic GET Request

import requests

# Define API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"

# Send GET request
response = requests.get(url)

# Print response
print(response.json())

Handling API Errors

if response.status_code == 200:
    print("Request successful:", response.json())
else:
    print("Error:", response.status_code)

Sending Data with a POST Request

data = {
    "title": "Automated Post",
    "body": "This post was created using Python.",
    "userId": 1
}

# Send POST request
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)

print(response.json())

Updating Data with a PUT Request

updated_data = {
    "id": 1,
    "title": "Updated Post Title",
    "body": "Updated post content.",
    "userId": 1
}

# Send PUT request
response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=updated_data)

print(response.json())

Deleting Data with a DELETE Request

response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")

if response.status_code == 200:
    print("Post deleted successfully.")
else:
    print("Error deleting post.")

Using API Authentication

Some APIs require authentication using API keys, OAuth tokens, or basic authentication.

Using API Key Authentication

headers = {
    "Authorization": "Bearer YOUR_API_KEY"
}

response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())

Using Basic Authentication

from requests.auth import HTTPBasicAuth

response = requests.get("https://api.example.com/secure-data", auth=HTTPBasicAuth("username", "password"))
print(response.json())

Using OAuth Authentication

headers = {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN"
}

response = requests.get("https://api.example.com/user/profile", headers=headers)
print(response.json())

Handling API Rate Limits

Some APIs limit the number of requests per second. To avoid being blocked, implement request delays:

import time

for i in range(5):
    response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
    print(response.json())
    time.sleep(2)  # Wait 2 seconds between requests

Working with Asynchronous API Requests (httpx)

For improved performance, use httpx for async API requests.

import httpx
import asyncio

async def fetch_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://jsonplaceholder.typicode.com/posts/1")
        print(response.json())

asyncio.run(fetch_data())

Downloading JSON Data and Converting to CSV/Excel

Saving API Data to JSON File

import json

# Fetch API data
response = requests.get("https://jsonplaceholder.typicode.com/posts")

# Save data to a JSON file
with open("data.json", "w") as file:
    json.dump(response.json(), file, indent=4)

print("Data saved to data.json")

Converting API Data to CSV

import csv

# Convert API response to CSV
data = response.json()
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    
    # Write headers
    writer.writerow(data[0].keys())
    
    # Write data
    for item in data:
        writer.writerow(item.values())

print("Data saved to data.csv")

Converting API Data to Excel

import pandas as pd

# Convert API response to DataFrame
df = pd.DataFrame(response.json())

# Save data to Excel
df.to_excel("data.xlsx", index=False)

print("Data saved to data.xlsx")

Automating API Reports via Email

import yagmail

# Send API report via email
yag = yagmail.SMTP("your_email@gmail.com", "your_password")
yag.send(
    to="recipient@example.com",
    subject="API Data Report",
    contents="Here is the latest API data report.",
    attachments="data.xlsx"
)

print("API report emailed successfully.")

Conclusion

This section covered automating API interactions, including making GET, POST, PUT, and DELETE requests, handling authentication, saving data in JSON/CSV/Excel, and sending reports via email. These techniques are useful for integrating APIs with automated workflows.

Would you like additional examples or modifications?

Popular Posts