Python: Pull Data From an API Into a Formatted Excel Report

⏱ 1 min readUpdated 28 September 2026

Combine APIs with Excel automation: one script fetches fresh data and produces a report your team opens as usual.

import requests, pandas as pd
from datetime import date
from openpyxl.styles import Font, PatternFill

URL = "https://api.example.com/orders"            # your system's API
HEAD = {"Authorization": "Bearer YOUR_KEY"}       # load from an environment variable in real use

rows = requests.get(URL, headers=HEAD, params={"from": "2020-09-01"}, timeout=60).json()["orders"]
df = pd.json_normalize(rows)
summary = (df.groupby("region", as_index=False)
             .agg(orders=("id", "count"), revenue=("amount", "sum"))
             .sort_values("revenue", ascending=False))

out = f"orders_{date.today():%Y-%m-%d}.xlsx"
with pd.ExcelWriter(out, engine="openpyxl") as xl:
    summary.to_excel(xl, "Summary", index=False)
    df.to_excel(xl, "Detail", index=False)
    ws = xl.sheets["Summary"]
    for c in ws[1]:
        c.font = Font(bold=True, color="FFFFFF"); c.fill = PatternFill("solid", fgColor="217346")
    ws.column_dimensions["A"].width = 16
    for cell in ws["C"][1:]:
        cell.number_format = "#,##0"
print("Saved", out)

Make it robust

  • timeout=60 so a hung API does not freeze the job.
  • raise_for_status() after the request, to fail loudly on 401/500 errors.
  • Handle pagination if the API returns results in pages (look for next in the response).
💡 Schedule it with Windows Task Scheduler (Action: python C:\reports\orders.py) and the report is waiting every morning.
✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong