Modern software frequently relies on APIsβApplication Programming Interfacesβto integrate services, retrieve data, and automate workflows. In Python, working with APIs is both accessible and powerful. Whether you want to pull weather data, automate deployments, interact with web services, or manage your own resources, Python provides robust tools like requests, httpx, and libraries for handling authentication, parsing data, and scheduling tasks.
This document provides an in-depth guide to using Python for API-driven automation. It covers:
An API allows two systems to communicate via a well-defined interface. Web APIs typically use HTTP, enabling access to data and functionality over the internet. Common examples include:
Key HTTP status codes:
pip install requests
import requests
response = requests.get('https://api.example.com/data')
print(response.status_code)
print(response.json())
params = {'q': 'python', 'limit': 10}
response = requests.get('https://api.example.com/search', params=params)
print(response.url)
print(response.json())
payload = {'name': 'Alice', 'age': 30}
response = requests.post('https://api.example.com/user', json=payload)
print(response.status_code, response.json())
update = {'age': 31}
response = requests.put('https://api.example.com/user/123', json=update)
print(response.status_code)
response = requests.delete('https://api.example.com/user/123')
print(response.status_code)
API_KEY = 'your_api_key_here'
headers = {'Authorization': f'Bearer {API_KEY}'}
response = requests.get('https://api.example.com/protected', headers=headers)
print(response.status_code, response.json())
from requests.auth import HTTPBasicAuth
response = requests.get('https://api.example.com/private', auth=HTTPBasicAuth('user', 'pass'))
print(response.status_code)
# Simplified example using client credentials grant
import requests
token_url = 'https://api.example.com/oauth2/token'
data = {'grant_type': 'client_credentials', 'client_id': 'xxx', 'client_secret': 'yyy'}
token_resp = requests.post(token_url, data=data)
token = token_resp.json()['access_token']
headers = {'Authorization': f'Bearer {token}'}
resp = requests.get('https://api.example.com/data', headers=headers)
print(resp.json())
def fetch_all():
url = 'https://api.example.com/items'
params = {'page': 1, 'per_page': 100}
items = []
while True:
resp = requests.get(url, params=params)
data = resp.json()
items.extend(data['items'])
if not data.get('next_page'):
break
params['page'] += 1
return items
def fetch_cursor():
url = 'https://api.example.com/stream'
cursor = None
items = []
while True:
resp = requests.get(url, params={'cursor': cursor})
data = resp.json()
items.extend(data['items'])
cursor = data.get('next_cursor')
if cursor is None:
break
return items
import time
response = requests.get(url)
reset = int(response.headers.get('X-Rate-Limit-Reset'))
remaining = int(response.headers.get('X-Rate-Limit-Remaining'))
if remaining == 0:
wait = reset - time.time()
time.sleep(max(wait, 0))
resp = requests.get(url)
if resp.status_code != 200:
raise Exception(f'Error: {resp.status_code}')
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(total=5, backoff_factor=1, status_forcelist=[429, 502, 503, 504])
session.mount('https://', HTTPAdapter(max_retries=retries))
resp = session.get(url)
print(resp.status_code)
resp = requests.get(url)
data = resp.json()
for item in data['items']:
print(item['id'], item['name'])
import xml.etree.ElementTree as ET
resp = requests.get('https://api.example.com/data.xml')
root = ET.fromstring(resp.content)
for elem in root.findall('.//item'):
print(elem.find('id').text, elem.find('name').text)
resp = requests.get(url)
data = resp.json()['results']
nested = [u['profile']['email'] for u in data]
print(nested)
import pandas as pd
resp = requests.get(url)
entries = resp.json()['items']
df = pd.DataFrame(entries)
print(df.head())
df.to_csv('output.csv', index=False)
df.to_json('output.json', orient='records')
import sqlite3
conn = sqlite3.connect('data.db')
df.to_sql('api_data', conn, if_exists='replace', index=False)
conn.close()
# cron entry to run every hour
0 * * * * /usr/bin/python3 /path/to/script.py
Use Task Scheduler to run the Python script at set intervals.
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=60)
def fetch_and_store():
resp = requests.get(url)
df = pd.DataFrame(resp.json()['items'])
df.to_csv('hourly.csv', index=False)
scheduler.start()
import requests
API_KEY = 'your_api_key'
url = 'https://api.weather.com/v3/wx/forecast/daily/5day'
params = {'postalKey': '12345:US', 'format': 'json', 'apiKey': API_KEY}
resp = requests.get(url, params=params)
forecast = resp.json()['temperatureMax']
for day, temp in enumerate(forecast):
if temp > 35:
print(f'Alert: Day {day} will be over 35Β°C: {temp}Β°C')
import requests
SLACK_WEBHOOK = 'https://hooks.slack.com/services/...'
def send_slack(message):
payload = {'text': message}
requests.post(SLACK_WEBHOOK, json=payload)
send_slack('Automation script completed successfully!')
import requests
token = 'ghp_xxx'
headers = {'Authorization': f'token {token}'}
issues = requests.get('https://api.github.com/repos/user/repo/issues', headers=headers).json()
for issue in issues:
if issue['state'] == 'open':
print(issue['number'], issue['title'])
from unittest.mock import patch
import requests
@patch('requests.get')
def test_fetch(mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {'items': [1, 2]}
result = fetch_all() # function from earlier
assert result == [1, 2]
import logging
logging.basicConfig(level=logging.INFO)
logging.info('Starting API automation')
resp = requests.get(url)
logging.debug(resp.text)
Python offers a rich ecosystem for automating tasks using APIs, from simple GET requests to full OAuth2 flows and scheduled pipelines. With libraries like requests, httpx, pandas, and APScheduler, you can build robust, scalable automation that interacts with services, handles data, and runs reliably over time.
This guide covered all major aspects required for API-based automation: HTTP mechanics, authentication, pagination, error handling, scheduling, real-world examples, and best practices. Whether you're monitoring systems, integrating services, or building data pipelines, mastering API workflows is a powerful skill that elevates your Python development.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved