← Back to Recipes
Google Sheets to chart
Fetch data from Google Sheets API and render a chart.
from google.oauth2 import service_account
from googleapiclient.discovery import build
from chart_output import ChartOutput
# Fetch from Sheets
creds = service_account.Credentials.from_service_account_file("creds.json")
sheets = build("sheets", "v4", credentials=creds)
result = sheets.spreadsheets().values().get(
spreadsheetId="YOUR_SHEET_ID", range="A1:B10"
).execute()
rows = result.get("values", [])
labels = [r[0] for r in rows[1:]]
data = [float(r[1]) for r in rows[1:]]
# Render chart
client = ChartOutput(api_key="YOUR_API_KEY")
buf = client.render(type="bar", data={"labels": labels, "datasets": [{"data": data}]})
with open("chart.png", "wb") as f:
f.write(buf)