🐍 Python Intermediate Featured

Convert API Response to Google Sheets

Push API data to Google Sheets in real time using Python and Google Apps Script.

461 views 20 mins Admin 10 months ago

About This Script

Automatically fetch data from any REST API and push it to Google Sheets. Great for dashboards, reporting, and data visualization.

What You'll Learn:

  • Authenticate with Google Sheets API
  • Parse JSON responses
  • Update sheets programmatically
  • Schedule with cron
Source Code
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import requests
import json

# Google Sheets Setup
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
client = gspread.authorize(creds)

# Open the sheet
sheet = client.open("API Data Sheet").sheet1

def fetch_api_data(url):
    response = requests.get(url)
    return response.json()

def write_to_sheet(data):
    # Clear existing data
    sheet.clear()
    
    # Write headers
    headers = list(data[0].keys())
    sheet.append_row(headers)
    
    # Write data rows
    for item in data:
        row = [item.get(key, "") for key in headers]
        sheet.append_row(row)
    
    print(f"✅ {len(data)} rows written to Google Sheets")

if __name__ == "__main__":
    api_url = "https://api.example.com/data"
    data = fetch_api_data(api_url)
    write_to_sheet(data)
Requirements
Google Cloud project, Service Account credentials, gspread library
Quick Actions
More in API & AI Integrations