Skip to main content
← Back to Recipes

Google Sheets to chart

Fetch data from Google Sheets API and render a chart.

python
import json, os, urllib.request from google.oauth2 import service_account from googleapiclient.discovery import build # 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 spec = {"type": "bar", "data": {"labels": labels, "datasets": [{"data": data}]}} req = urllib.request.Request( "https://www.chart-output.com/api/v1/render", data=json.dumps(spec).encode(), headers={ "Authorization": f"Bearer {os.environ['CHART_OUTPUT_API_KEY']}", "Content-Type": "application/json", }, method="POST", ) with urllib.request.urlopen(req) as resp, open("chart.png", "wb") as f: f.write(resp.read())