Skip to content

How to work with the Google Sheets API and Python

Learn how to use Google Sheets API in Python. We are using the gspread module for this.

Learn how to use Google Sheets API in Python. We are using the gspread module for this. It's super simple to setup a project, and then access and modify our spreadsheet with a Python script. Google Sheets can be pretty powerful and used as a backend to store some data for your web applications.

You can find and test the code on GitHub.

Check out the gspread documentation here.


  • Google Developer Console:
  • New Project -> Activate Drive and Sheets API
  • Create credentials

    • -> service account -> name + role=editor
    • ->create key and download json
  • Share client_email from json in your worksheet

Use the gspread module


pip install gspread


import gspread # 

gc = gspread.service_account(filename='credentials.json')
sh = gc.open_by_key("xxxx") # or by sheet name:"TestList")
worksheet = sh.sheet1

### retrieve data ###
res = worksheet.get_all_records() # list of dictionaries
res = worksheet.get_all_values() # list of lists

values_list = worksheet.row_values(1)
values_list = worksheet.col_values(1)

print(worksheet.row_count, worksheet.col_count)


user = ["Susan", "28", "Sydney"]
#worksheet.insert_row(user, 3)
#worksheet.insert_row(user, 2) #same with column
#worksheet.update_cell(1,2, value)


Create client manually

Use the following if you have the credentials already loaded and in JSON format:

import json
from google.oauth2.service_account import (
    Credentials as ServiceAccountCredentials,
with open('credentials.json', 'r') as f:
    credentials = json.load(f)
creds = ServiceAccountCredentials.from_service_account_info(credentials, scopes=DEFAULT_SCOPES)
gc = gspread.Client(auth=creds)

FREE VS Code / PyCharm Extensions I Use

鉁 Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹