
Python for Automation, Part 3: API, JSON, Query Repetitions, and Secrets
🌐 Machine-translated from Russian. Show original
In this part:
requests or httpx#
| requests | httpx | |
|---|---|---|
| Style | synchronous | synchronous and asynchronous |
| HTTP/2 | no | yes (packet httpx[http2]) |
| Default timeout | no (can wait forever) | 5 seconds |
| Repeats | after urllib3.Retry | only the connection repeat; the rest is your own code |
| Where | appears in a huge number of examples and libraries | in modern projects, python-telegram-bot runs on top of it |
Both libraries are good. In new scripts, httpx is more convenient: the same API, plus async when needed (the bot in part 5 is asynchronous).
uv add httpx
First request#
An example with a real public API — what is the latest version of the project on GitHub. It's convenient to keep track of software updates you maintain.
import httpx
REPOS = ["prometheus/prometheus", "grafana/grafana", "astral-sh/uv"]
with httpx.Client(timeout=10, headers={"Accept": "application/vnd.github+json"}) as client:
for repo in REPOS:
r = client.get(f"https://api.github.com/repos/{repo}/releases/latest")
r.raise_for_status() # 4xx/5xx → исключение, а не тихая ошибка
data = r.json()
print(f"{repo:30} {data['tag_name']:12} {data['published_at'][:10]}")
Without a token, GitHub allows a small number of requests per hour from a single IP. With a token, the limit is higher — we pass it from the environment (below).
Parameters, POST, and JSON#
# GET с параметрами — httpx сам закодирует их в URL
r = client.get("https://api.example.kz/v1/orders", params={"date_from": "2026-11-01", "status": "paid"})
# POST с JSON-телом
r = client.post("https://api.example.kz/v1/tickets", json={"title": "Диск заполнен", "priority": "high"})
print(r.status_code, r.json())
Secrets: tokens only from the environment#
import httpx
from pyreports.config import need
token = need("EXAMPLE_API_TOKEN")
client = httpx.Client(
base_url="https://api.example.kz/v1",
headers={"Authorization": f"Bearer {token}"},
timeout=httpx.Timeout(10, connect=5),
)
Rules:
- Token — in
.env(locally), inEnvironmentFilesystemd or in job environment variables (server), in CI secrets. Not in code, not in Git, not in command-line arguments (they are visible in the process list). - Do not log URLs and headers entirely. Some APIs (for example, the Telegram Bot API) pass the token directly to the address. httpx at the INFO level logs every URL — raise its level:
logging.getLogger("httpx").setLevel(logging.WARNING). - For Windows scripts run by humans, a password can be stored in Windows Credential Manager via the
keyringpackage. - Leaked token — immediately recall and issue a new one; deleting it from the Git history does not help.
Corporate certificate and SSL#
Internal sites are often signed by a corporate certification authority, and the request drops with CERTIFICATE_VERIFY_FAILED. Do not disable validation (verify=False) — this opens the way to traffic interception. Specify the root certificate:
import ssl
import httpx
ctx = ssl.create_default_context(cafile="certs/corp-root-ca.pem")
client = httpx.Client(verify=ctx)
Another option is the truststorepackage, which forces Python to trust the Windows or Linux system certificate store, where the corporate CA is usually already set by Group Policy.
Repetitions and Pauses#
The network and third-party services sometimes respond with errors. The correct response is to repeat the request with an increasing pause, but only for temporary errors: 429 (too many requests), 500, 502, 503, 504, and connection drops. Repeating errors 400, 401, 403, 404 is pointless.
import logging
import random
import time
import httpx
log = logging.getLogger(__name__)
RETRY_STATUS = {429, 500, 502, 503, 504}
def request_with_retry(client: httpx.Client, method: str, url: str, attempts: int = 5, **kwargs) -> httpx.Response:
for attempt in range(1, attempts + 1):
try:
r = client.request(method, url, **kwargs)
except httpx.TransportError as e: # таймаут, обрыв, DNS
if attempt == attempts:
raise
wait = 2 ** attempt + random.random()
log.warning("%s %s: %s, повтор через %.1f с", method, url, type(e).__name__, wait)
time.sleep(wait)
continue
if r.status_code in RETRY_STATUS and attempt < attempts:
try:
wait = float(r.headers.get("Retry-After", "")) # сервер сам сказал, сколько ждать
except ValueError:
wait = 2 ** attempt + random.random()
log.warning("%s %s: HTTP %s, повтор через %.1f с", method, url, r.status_code, wait)
time.sleep(min(wait, 60))
continue
r.raise_for_status()
return r
raise RuntimeError("недостижимо")
⚠️ It's safe to repeat POST only if the API supports idempotency (e.g.,
Idempotency-Keyheader), otherwise you can create two requests or two payments.
A ready-made alternative is the tenacity library (decorator @retry). For requests, repeats are configured as usual:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=5, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["GET"])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
r = session.get("https://api.example.kz/v1/orders", timeout=(5, 30)) # (соединение, чтение) — таймаут обязателен
Pagination#
APIs deliver large lists of pages. Two common options are the page number and the cursor.
def fetch_all(client: httpx.Client, url: str, params: dict | None = None) -> list[dict]:
"""Вариант с курсором: ответ вида {"items": [...], "next_cursor": "..."}."""
items, params = [], dict(params or {})
while True:
data = request_with_retry(client, "GET", url, params=params).json()
items.extend(data["items"])
cursor = data.get("next_cursor")
if not cursor:
return items
params["cursor"] = cursor
Field names (items, next_cursor, page, Link-header on GitHub) can be found in the documentation of the specific API.
JSON: save, read, compare#
import json
from pathlib import Path
state_file = Path("state/releases.json")
old = json.loads(state_file.read_text(encoding="utf-8")) if state_file.exists() else {}
new = {"prometheus/prometheus": "v3.16.0"} # то, что получили из API
changed = {k: v for k, v in new.items() if old.get(k) != v}
if changed:
print("Новые версии:", changed) # здесь — отправка в Telegram из части 5
state_file.parent.mkdir(exist_ok=True)
state_file.write_text(json.dumps(new, ensure_ascii=False, indent=2), encoding="utf-8")
ensure_ascii=False — so that the Cyrillic script in the file is readable, not converted into codes.
Asynchronous: many requests at once#
If you need to query a hundred addresses, consecutive queries will take minutes. From httpx.AsyncClient to seconds:
import asyncio
import httpx
URLS = ["https://itgov.kz", "https://www.python.org", "https://example.com"]
async def check(client: httpx.AsyncClient, url: str) -> tuple[str, str]:
try:
r = await client.get(url)
return url, f"{r.status_code} за {r.elapsed.total_seconds():.2f} с"
except httpx.HTTPError as e:
return url, f"ошибка: {type(e).__name__}"
async def main() -> None:
limits = httpx.Limits(max_connections=20) # не больше 20 одновременных соединений
async with httpx.AsyncClient(timeout=10, follow_redirects=True, limits=limits) as client:
for url, result in await asyncio.gather(*(check(client, u) for u in URLS)):
print(f"{url:30} {result}")
asyncio.run(main())
Next — administration: SSH, WinRM, and Active Directory: Python for automation, part 4: ping and ports, SSH via paramiko, PowerShell, and WinRM, Active Directory via ldap3.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.