### Install gspread Source: https://docs.gspread.org/en/v6.2.1/_sources/index.rst.txt Install the gspread library using pip. Requires Python 3+. ```sh pip install gspread ``` -------------------------------- ### Example Service Account JSON Credentials Source: https://docs.gspread.org/en/v6.2.1/oauth2.html This is an example of the JSON file downloaded when creating a service account key. It contains sensitive credentials. ```json { "type": "service_account", "project_id": "api-project-XXX", "private_key_id": "2cd … ba4", "private_key": "-----BEGIN PRIVATE KEY-----\nNrDyLw … jINQh/9\n-----END PRIVATE KEY-----\n", "client_email": "473000000000-yoursisdifferent@developer.gserviceaccount.com", "client_id": "473 … hd.apps.googleusercontent.com", ... } ``` -------------------------------- ### Quick gspread Example Source: https://docs.gspread.org/en/v6.2.1/index.html Demonstrates basic gspread operations: authenticating, opening a spreadsheet, updating cell ranges and single cells, and formatting a header. ```python import gspread gc = gspread.service_account() # Open a sheet from a spreadsheet in one go wks = gc.open("Where is the money Lebowski?").sheet1 # Update a range of cells using the top left corner address wks.update([[1, 2], [3, 4]], 'A1') # Or update a single cell wks.update_acell('B42', "it's down there somewhere, let me take another look.") # Format the header wks.format('A1:B1', {'textFormat': {'bold': True}}) ``` -------------------------------- ### Quick Start with gspread Source: https://docs.gspread.org/en/v6.2.1/_sources/index.rst.txt Demonstrates basic gspread operations: authenticating, opening a spreadsheet, updating cell ranges and single cells, and formatting headers. Assumes you have authenticated using service_account(). ```python import gspread gc = gspread.service_account() # Open a sheet from a spreadsheet in one go wks = gc.open("Where is the money Lebowski?").sheet1 # Update a range of cells using the top left corner address wks.update([[1, 2], [3, 4]], 'A1') # Or update a single cell wks.update_acell('B42', "it's down there somewhere, let me take another look.") # Format the header wks.format('A1:B1', {'textFormat': {'bold': True}}) ``` -------------------------------- ### Expand Table from Starting Cell Source: https://docs.gspread.org/en/v6.2.1/user-guide.html Use `worksheet.expand()` starting from a cell to extract a data table. The table extends right and down until the first empty cell or the sheet edge. ```python worksheet.expand("A2") [ ["Batman", "DC", "Very rich"], ["DeadPool", "Marvel", "self healing"], ["Superman", "DC", "super human"], ] ``` -------------------------------- ### Expand Table from Starting Cell Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Extracts a data table starting from the specified cell. The table extends right and down until the first empty cell or the sheet boundary. ```python worksheet.expand("A2") [ ["Batman", "DC", "Very rich"], ``` -------------------------------- ### Open Spreadsheet and Get Worksheet Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Opens a spreadsheet by its title and then retrieves a specific worksheet by its title. Ensure the spreadsheet and worksheet exist. ```python >>> sht = client.open('Sample one') >>> worksheet = sht.worksheet('Annual bonuses') ``` -------------------------------- ### Get All Values from Worksheet Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve all non-empty values from the entire worksheet. This is a simple way to get all data when no specific range is required. ```python worksheet.get() ``` -------------------------------- ### Get All Values from First Row Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Fetches all values from the first row of a worksheet as a list. This is a convenient way to get a single row's data. ```python values_list = worksheet.row_values(1) ``` -------------------------------- ### Authenticate with Service Account (Using google-auth library) Source: https://docs.gspread.org/en/v6.2.1/_sources/oauth2.rst.txt This demonstrates the underlying mechanism gspread uses for authentication with a service account, utilizing the `google-auth` library. It shows how to load credentials from a file and specify the required scopes. ```python from google.oauth2.service_account import Credentials scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] credentials = Credentials.from_service_account_file( 'path/to/the/downloaded/file.json', scopes=scopes ) gc = gspread.authorize(credentials) ``` -------------------------------- ### Get Cell Formula Value Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves the formula of a specific cell using `ValueRenderOption.formula`. This allows you to get the exact formula string used in the cell. ```python from gspread.utils import ValueRenderOption worksheet.get("G6", value_render_option=ValueRenderOption.formula) ``` -------------------------------- ### service_account() Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Initializes gspread using a service account. This is suitable for server-to-server interactions where direct user authorization is not required. ```APIDOC ## service_account() ### Description Initializes gspread using a service account. ### Method `service_account()` ### Parameters This function typically takes a path to a service account JSON key file as an argument, but specific parameter details are not provided in the source. ``` -------------------------------- ### Service Account Authentication from File Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authenticate using a service account by providing the path to the JSON key file. The default path is ~/.config/gspread/service_account.json. ```python gc = gspread.service_account() ``` -------------------------------- ### Client.create() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Creates a new, empty spreadsheet with a specified title and optionally places it in a specific folder. ```APIDOC ## Client.create() ### Description Creates a new spreadsheet. ### Method `create(_title : str_, _folder_id : str | None = None_) → Spreadsheet` ### Parameters #### Path Parameters - **title** (str) - Required - A title of a new spreadsheet. - **folder_id** (str) - Optional - Id of the folder where we want to save the spreadsheet. ### Returns - a `Spreadsheet` instance. ``` -------------------------------- ### Get Worksheet Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Retrieves a specific worksheet by its title. ```APIDOC ## Get Worksheet ### Description Returns a Worksheet object corresponding to the specified title. ### Method `sh.worksheet(title)` ### Parameters * **title** (str) - The title of the worksheet to retrieve. ``` -------------------------------- ### Authenticate with Service Account (Default Path) Source: https://docs.gspread.org/en/v6.2.1/_sources/oauth2.rst.txt Use this method to authenticate with gspread using a service account. The credentials file is expected to be at the default location: `~/.config/gspread/service_account.json` or `%APPDATA%\gspread\service_account.json` on Windows. ```python import gspread gc = gspread.service_account() sh = gc.open("Example spreadsheet") print(sh.sheet1.get('A1')) ``` -------------------------------- ### Values Get Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Retrieves values from a specified range in the spreadsheet. ```APIDOC ## Values Get ### Description Fetches values from a specific range within the spreadsheet. This method directly calls the `GET spreadsheets//values/` API endpoint. ### Method `sh.values_get(range, params=None)` ### Parameters * **range** (str) - The A1 notation of the range from which to retrieve values. * **params** (dict, optional) - Query parameters for the Values Get request. ``` -------------------------------- ### authorize() Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authorizes the gspread client with provided credentials. ```APIDOC ## authorize() ### Description Authorizes the gspread client using credentials obtained from an OAuth flow or service account. This is a general-purpose authorization function. ### Parameters - **credentials** (oauth2client.client.OAuth2Credentials or google.oauth2.service_account.Credentials) - Required - The authenticated credentials object. ### Returns - A `gspread.Client` instance authenticated with the provided credentials. ``` -------------------------------- ### delete_rows Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Deletes one or more rows from the worksheet starting at a specified index. ```APIDOC ## delete_rows ### Description Deletes multiple rows from the worksheet at the specified index. ### Parameters #### Path Parameters * **start_index** (int) - Index of a first row for deletion. * **end_index** (int | None) - Index of a last row for deletion. When end_index is not specified this method only deletes a single row at `start_index`. ``` -------------------------------- ### Basic OAuth Authentication with gspread Source: https://docs.gspread.org/en/v6.2.1/oauth2.html Use this for initial authentication where gspread will prompt the user to authorize access via a browser. Credentials are automatically stored for future use. ```python import gspread gc = gspread.oauth() sh = gc.open("Example spreadsheet") print(sh.sheet1.get('A1')) ``` -------------------------------- ### delete_columns Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Deletes one or more columns from the worksheet starting at a specified index. ```APIDOC ## delete_columns ### Description Deletes multiple columns from the worksheet at the specified index. ### Parameters #### Path Parameters * **start_index** (int) - Index of a first column for deletion. * **end_index** (int | None) - Index of a last column for deletion. When end_index is not specified this method only deletes a single column at `start_index`. ``` -------------------------------- ### Authorize with Custom HTTP Client Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Instantiate a client using a custom HTTP client factory, such as one that implements backoff strategies for rate limiting. ```python gc = gspread.authorize(_credentials, http_client=gspread.http_client.BackOffHTTPClient) ``` -------------------------------- ### get_a1_from_absolute_range Source: https://docs.gspread.org/en/v6.2.1/api/utils.html Get the A1 notation from an absolute range name, stripping the sheet name if present. ```APIDOC ## get_a1_from_absolute_range ### Description Get the A1 notation from an absolute range name, stripping the sheet name if present. ### Parameters #### Path Parameters - **range_name** (_str_): Required - The range name to process (e.g., "Sheet1!A1:B2" or "A1:B2"). ### Returns - **str**: The A1 notation of the range name (e.g., "A1:B2"). ``` -------------------------------- ### Authorize with Existing Credentials Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Use this helper function to create a gspread client instance from pre-existing Google API credentials. ```python gc = gspread.authorize(_credentials) ``` -------------------------------- ### Values Batch Get Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Retrieves values from multiple ranges in the spreadsheet in a single batch request. ```APIDOC ## Values Batch Get ### Description Fetches values from multiple specified ranges within the spreadsheet in a single batch request. This method maps to the `spreadsheets//values:batchGet` API endpoint. ### Method `sh.values_batch_get(ranges, params=None)` ### Parameters * **ranges** (list) - A list of ranges in A1 notation from which to retrieve values. * **params** (dict, optional) - Query parameters for the Values Batch Get request. ``` -------------------------------- ### unhide_rows Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Explicitly unhides the given row index range. Row indices start from 0. ```APIDOC ## unhide_rows ### Description Explicitly unhide the given row index range. Index start from 0. ### Method `unhide_rows(start: int, end: int)` ### Parameters #### Path Parameters - **start** (int) - Required - The (inclusive) starting row to hide - **end** (int) - Required - The (exclusive) end row to hide ``` -------------------------------- ### Service Account with Custom Filename Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Provide a specific path to your service account JSON key file if it's not located at the default path. ```python gc = gspread.service_account(filename='/path/to/your/service_account.json') ``` -------------------------------- ### unhide_columns Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Explicitly unhides the given column index range. Column indices start from 0. ```APIDOC ## unhide_columns ### Description Explicitly unhide the given column index range. Index start from 0. ### Method `unhide_columns(start: int, end: int)` ### Parameters #### Path Parameters - **start** (int) - Required - The (inclusive) starting column to hide - **end** (int) - Required - The (exclusive) end column to hide ``` -------------------------------- ### local_server_flow() Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Initiates an OAuth 2.0 flow using a local development server. ```APIDOC ## local_server_flow() ### Description Starts an OAuth 2.0 authorization flow that requires a local web server to handle the redirect from Google's authorization server. This is typically used for desktop applications or development environments. ### Parameters - **client_config** (dict) - Required - A dictionary containing client ID and client secret. - **scope** (list) - Optional - A list of OAuth scopes to request. ### Returns - A `gspread.auth.FlowCallable` object representing the authorization flow. ``` -------------------------------- ### Unhide Rows Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Explicitly unhides a specified range of rows. Row indices start from 0. ```python unhide_rows(_start : int_, _end : int_) ``` -------------------------------- ### Client.open() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Opens a spreadsheet by its title. ```APIDOC ## Client.open() ### Description Opens a spreadsheet by its title. ### Method `open(_title : str_) → Spreadsheet` ### Parameters #### Path Parameters - **title** (str) - Required - The title of the spreadsheet to open. ``` -------------------------------- ### Authenticate with Service Account (Credentials as Dictionary) Source: https://docs.gspread.org/en/v6.2.1/_sources/oauth2.rst.txt Authenticate gspread using service account credentials provided directly as a Python dictionary. This is an alternative to loading from a JSON file. ```python import gspread credentials = { "type": "service_account", "project_id": "api-project-XXX", "private_key_id": "2cd … ba4", "private_key": "-----BEGIN PRIVATE KEY-----\nNrDyLw … jINQh/9\n-----END PRIVATE KEY-----", "client_email": "473000000000-yoursisdifferent@developer.gserviceaccount.com", "client_id": "473 … hd.apps.googleusercontent.com", ... } # Note: gspread.service_account() does not directly accept a dictionary. # This example illustrates the structure of credentials that would be loaded. # To use a dictionary, you would typically pass it to a lower-level auth function # or construct a Credentials object from it if supported by the google-auth library. ``` -------------------------------- ### Unhide Columns Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Explicitly unhides a specified range of columns. Column indices start from 0. ```python unhide_columns(_start : int_, _end : int_) ``` -------------------------------- ### rows_auto_resize Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Updates the size of rows or columns in the worksheet. Row and column indices start from 0. ```APIDOC ## rows_auto_resize ### Description Updates the size of rows or columns in the worksheet. Indices start from 0. ### Parameters #### Path Parameters * **start_row_index** (int) - Required - The index (inclusive) to begin resizing. * **end_row_index** (int) - Required - The index (exclusive) to finish resizing. ``` -------------------------------- ### Client.open_by_url() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Opens a spreadsheet using its full URL. ```APIDOC ## Client.open_by_url() ### Description Opens a spreadsheet by its URL. ### Method `open_by_url(_url : str_) → Spreadsheet` ### Parameters #### Path Parameters - **url** (str) - Required - The full URL of the spreadsheet. ``` -------------------------------- ### Get Values from Columns Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve all values from specified columns. This method is useful when you need data from entire columns. ```python worksheet.get('A:B') ``` -------------------------------- ### Client.openall() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Opens all spreadsheets accessible by the authenticated user. ```APIDOC ## Client.openall() ### Description Opens all spreadsheets. ### Method `openall() → list[Spreadsheet]` ``` -------------------------------- ### Client.open_by_key() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Opens a spreadsheet using its unique file ID (key). ```APIDOC ## Client.open_by_key() ### Description Opens a spreadsheet by its key. ### Method `open_by_key(_key : str_) → Spreadsheet` ### Parameters #### Path Parameters - **key** (str) - Required - The unique file ID (key) of the spreadsheet. ``` -------------------------------- ### Get a specific cell Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve a Cell object from a specific row and column. The value_render_option can be used to control how values are rendered. ```python >>> worksheet.cell(1, 1) ``` -------------------------------- ### Get Worksheet by ID Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Retrieve a worksheet from a spreadsheet using its unique ID. The ID can be found in the spreadsheet's URL. ```python >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet_by_id(123456) ``` -------------------------------- ### BackOffHTTPClient Initialization Source: https://docs.gspread.org/en/v6.2.1/api/http_client.html Initializes an HTTP client with exponential backoff retries. This client automatically retries requests that fail due to rate limits, preventing application failures. ```python _gspread.BackOffHTTPClient(_auth : Credentials_, _session : Session | None = None_) ``` -------------------------------- ### OAuth Authentication from Dictionary (Local Server Flow) Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Use this method for OAuth authentication when running locally and wanting to use the default local server flow. It opens the authorization URL in the user's browser. ```python gc = gspread.oauth_from_dict() ``` -------------------------------- ### Get List of Worksheets Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves a list of all worksheet objects within a spreadsheet. This is useful for iterating or inspecting all available sheets. ```python worksheet_list = sh.worksheets() ``` -------------------------------- ### Client.list_spreadsheet_files() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Lists all spreadsheet files accessible by the authenticated user. ```APIDOC ## Client.list_spreadsheet_files() ### Description Lists all spreadsheet files. ### Method `list_spreadsheet_files() → Any` ``` -------------------------------- ### Write Array to Worksheet Source: https://docs.gspread.org/en/v6.2.1/user-guide.html Updates a worksheet with array data starting from the specified cell. Ensure the array is in a compatible format. ```python worksheet.update(array.tolist(), 'A2') ``` -------------------------------- ### Get column values Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieves all values from a specified column. Empty cells are returned as None. The value_render_option can be used to control rendering. ```python worksheet.col_values(2) ``` -------------------------------- ### Authenticate with gspread using google-auth library Source: https://docs.gspread.org/en/v6.2.1/oauth2.html This demonstrates the underlying authentication mechanism using google-auth Credentials. It's an alternative to the direct gspread service_account() method and requires specifying scopes. ```python from google.oauth2.service_account import Credentials scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] credentials = Credentials.from_service_account_file( 'path/to/the/downloaded/file.json', scopes=scopes ) gc = gspread.authorize(credentials) ``` -------------------------------- ### Get Major Dimension of ValueRange Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Accesses the major dimension property of a ValueRange object to determine if the data is oriented by rows or columns. ```python >>> worksheet.get("A1:B2").major_dimension ROW ``` -------------------------------- ### authorize() Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Provides a way to authorize gspread using an existing OAuth2 session or credentials object. This is an alternative to directly using oauth() or service_account(). ```APIDOC ## authorize() ### Description Authorizes gspread using an existing OAuth2 session or credentials object. ### Method `authorize()` ### Parameters This function typically accepts an authenticated credentials object, but specific parameter details are not provided in the source. ``` -------------------------------- ### Authenticate with Service Account (Custom Path) Source: https://docs.gspread.org/en/v6.2.1/_sources/oauth2.rst.txt Authenticate with gspread using a service account when your credentials file is not in the default location. Specify the path to your JSON credentials file using the `filename` argument. ```python gc = gspread.service_account(filename='path/to/the/downloaded/file.json') ``` -------------------------------- ### Authenticate with OAuth (Local Server) Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Use this for interactive authentication where the authorization URL is opened in the user's browser. ```python gc = gspread.oauth() ``` -------------------------------- ### Get Worksheet by Index Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Retrieve a worksheet from a spreadsheet using its zero-based index. Ensure the index is valid to avoid WorksheetNotFound errors. ```python >>> sht = client.open('My fancy spreadsheet') >>> worksheet = sht.get_worksheet(2) ``` -------------------------------- ### StrEnum Source: https://docs.gspread.org/en/v6.2.1/api/utils.html Base class for string enumerations. ```APIDOC ## StrEnum ### Description Base class for string enumerations. Provides string representation for enum members. ``` -------------------------------- ### Get All Worksheet Values as List of Lists Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Fetches all values from a worksheet and returns them as a list of lists. Suitable for direct data processing. ```python list_of_lists = worksheet.get_all_values() ``` -------------------------------- ### Open Spreadsheet by URL Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Opens a spreadsheet by providing its full URL. This is a convenient method if you have the URL readily available. ```python sht2 = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') ``` -------------------------------- ### Get All Values from First Column Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Fetches all values from the first column of a worksheet as a list. Useful for retrieving data from a single column. ```python values_list = worksheet.col_values(1) ``` -------------------------------- ### Authenticate with OAuth (Console Flow) Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Use this when running in an environment without a browser. The user copies an authorization code into the application. ```python gc = gspread.oauth(flow=gspread.auth.console_flow) ``` -------------------------------- ### Access Default Worksheet Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Accesses the default worksheet, typically named 'Sheet1'. This provides a quick way to get the primary worksheet. ```python worksheet = sh.sheet1 ``` -------------------------------- ### Get Values from a Range Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve values from a specified range of cells using A1 notation. Supports ranges like 'A1:B2'. ```python worksheet.get('A1:B2') ``` -------------------------------- ### Authenticate with Service Account Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Use this method for server-to-server authentication. It requires a service account JSON key file. ```python gc = gspread.service_account() ``` -------------------------------- ### Authenticate with OAuth (Local Server Flow) Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authenticate using OAuth 2.0 with the default local server flow. This will open an authorization URL in your browser. ```python gc = gspread.oauth() ``` -------------------------------- ### Get Specific Cell Value Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve the value of a single cell by specifying its A1 notation. Useful for accessing individual data points. ```python worksheet.get('A1') ``` -------------------------------- ### Get Values from Worksheet Range Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieves values from a specified range in the worksheet. The result is a ValueRange object, which behaves like a list of lists. ```python >>> worksheet.get("A1:B2") [ [ "A1 value", "B1 values", ], [ "A2 value", "B2 value", ] ] ``` -------------------------------- ### Service Account Authentication from Dictionary Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authenticate using a service account by providing the service account details directly as a Python dictionary. ```python gc = gspread.service_account_from_dict(info=my_service_account_info) ``` -------------------------------- ### HTTPClient.fetch_sheet_metadata Source: https://docs.gspread.org/en/v6.2.1/api/http_client.html Retrieve the metadata of a spreadsheet without fetching its cell data. This is useful for getting information like sheet names, IDs, and properties. ```APIDOC ## HTTPClient.fetch_sheet_metadata ### Description Retrieve the metadata from the spreadsheet by default **does not get the cells data**. It only retrieves the metadata from the spreadsheet. ### Method GET ### Endpoint `spreadsheets/{id}` ### Parameters #### Path Parameters - **id** (str) - Required - The spreadsheet ID key. #### Query Parameters - **params** (dict) - Optional - The HTTP params for the GET request. By default sets the parameter `includeGridData` to `false`. ### Response #### Success Response (200) - **spreadsheet_metadata** (dict) - The raw spreadsheet metadata. ### Response Example ```json { "spreadsheet_metadata": { "spreadsheetId": "12345abcde", "properties": { "title": "My Spreadsheet", "locale": "en_US" }, "sheets": [ { "properties": { "sheetId": 0, "title": "Sheet1" } } ] } } ``` ``` -------------------------------- ### show Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Displays the current worksheet in the UI. ```APIDOC ## show ### Description Show the current worksheet in the UI. ``` -------------------------------- ### Get Cell Formula by A1 Notation Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves the formula of a cell using its A1 notation, by specifying `value_render_option='FORMULA'`. This allows inspection of calculations. ```python cell = worksheet.acell('B1', value_render_option='FORMULA').value ``` -------------------------------- ### OAuth Authentication from Dictionary (Console Flow) Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Use this method for OAuth authentication when a local server flow is not suitable. The user is prompted to open a URL and paste an authorization code back into the console. ```python gc = gspread.oauth_from_dict(flow=gspread.auth.console_flow) ``` -------------------------------- ### Auto-resize columns Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Adjusts the size of columns within a specified range. Indices start from 0. Available from version 3.4, changed in 5.3.3. ```python worksheet.columns_auto_resize(0, 5) ``` -------------------------------- ### Authenticate with OAuth (Console Flow) Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authenticate using OAuth 2.0 with the console flow. The user is instructed to open an authorization URL and paste the code back into the application. ```python gc = gspread.oauth(flow=gspread.auth.console_flow) ``` -------------------------------- ### Authenticate with OAuth (Custom Credentials Path) Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authenticate using OAuth 2.0 while specifying custom file paths for credentials and authorized user information. ```python gc = gspread.oauth( credentials_filename='/alternative/path/credentials.json', authorized_user_filename='/alternative/path/authorized_user.json', ) ``` -------------------------------- ### Get All Notes from Worksheet Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieves all notes from the worksheet as a list of lists. The resulting matrix may not be square; use gspread.utils.fill_gaps to ensure a rectangular shape. ```python >>> worksheet.get_notes() [ ["A1"], ["", "B2"] ] ``` ```python >>> arr = worksheet.get_notes() >>> gspread.utils.fill_gaps(arr, len(arr), max(len(a) for a in arr), None) [ ["A1", ""], ["", "B2"] ] ``` -------------------------------- ### Get Values from Named Range Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve values from a pre-defined named range within the sheet. This simplifies accessing frequently used data blocks. ```python worksheet.get('my_range') ``` -------------------------------- ### Create Assertion Session with Authlib Source: https://docs.gspread.org/en/v6.2.1/advanced.html This function creates an authenticated session using Authlib for token management, suitable for scenarios requiring custom token handling. Ensure 'your-google-conf.json' contains your service account credentials. ```python import json from gspread import Client from authlib.integrations.requests_client import AssertionSession def create_assertion_session(conf_file, scopes, subject=None): with open(conf_file, 'r') as f: conf = json.load(f) token_url = conf['token_uri'] issuer = conf['client_email'] key = conf['private_key'] key_id = conf.get('private_key_id') header = {'alg': 'RS256'} if key_id: header['kid'] = key_id # Google puts scope in payload claims = {'scope': ' '.join(scopes)} return AssertionSession( grant_type=AssertionSession.JWT_BEARER_GRANT_TYPE, token_endpoint=token_url, issuer=issuer, audience=token_url, claims=claims, subject=subject, key=key, header=header, ) scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive', ] session = create_assertion_session('your-google-conf.json', scopes) gc = Client(None, session) wks = gc.open("Where is the money Lebowski?").sheet1 wks.update_acell('B2', "it's down there somewhere, let me take another look.") # Fetch a cell range cell_list = wks.range('A1:B7') ``` -------------------------------- ### Get Worksheet by Title Source: https://docs.gspread.org/en/v6.2.1/api/models/spreadsheet.html Retrieves a specific worksheet from a spreadsheet using its title. If multiple worksheets share the same title, the first one found will be returned. ```APIDOC ## worksheet(title: str) ### Description Returns a worksheet with the specified title. ### Parameters #### Path Parameters - **title** (str) - Required - The title of the worksheet to retrieve. ### Returns - an instance of `gspread.worksheet.Worksheet`. ### Raises - `WorksheetNotFound`: if the worksheet with the given title cannot be found. ### Example ```python sht = client.open('Sample one') worksheet = sht.worksheet('Annual bonuses') ``` ``` -------------------------------- ### Authorize with Custom Session Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Provide your own `requests.Session` object for managing HTTP requests. Use `None` for credentials when providing a custom session. ```python my_session = requests.Session() gc = gspread.authorize(None, session=my_session) ``` -------------------------------- ### Get Cell Value by Row and Column Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves the value of a cell using its row and column coordinates (1-based index). This is useful for programmatic access. ```python val = worksheet.cell(1, 2).value ``` -------------------------------- ### oauth() Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Authenticates using OAuth 2.0 with user consent. ```APIDOC ## oauth() ### Description Initiates the OAuth 2.0 flow to authenticate the user. This method will typically open a browser window for the user to grant permissions. ### Parameters - **credentials_file** (str) - Optional - Path to the JSON file containing OAuth 2.0 client credentials. - **client_config** (dict) - Optional - A dictionary containing client ID and client secret if `credentials_file` is not provided. - **scope** (list) - Optional - A list of OAuth scopes to request. ### Returns - A `gspread.Client` instance authenticated via OAuth 2.0. ``` -------------------------------- ### gspread.authorize Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Login to Google API using OAuth2 credentials. This is a helper function to instantiate a client. ```APIDOC ## gspread.authorize ### Description Login to Google API using OAuth2 credentials. This is a shortcut/helper function which instantiates a client using http_client. By default `gspread.HTTPClient` is used. It can take an additional requests.Session object in order to provide you own session object. Note: When providing your own requests.Session object, use the value None as credentials. ### Parameters #### Parameters - **_credentials** (~google.auth.credentials.Credentials_) – - **_http_client** (~typing.Type[~gspread.http_client.HTTPClient] = _) – - **_session** (~requests.Session | None = None_) – ### Returns An instance of the class produced by http_client. ### Return type `gspread.client.Client` ``` -------------------------------- ### gspread.spreadsheet.Spreadsheet Methods Source: https://docs.gspread.org/en/v6.2.1/genindex.html Methods available on a gspread.spreadsheet.Spreadsheet object for managing spreadsheets. ```APIDOC ## Spreadsheet Methods ### `named_range()` **Description**: Retrieves information about named ranges in the spreadsheet. ### `remove_permissions()` **Description**: Removes all permissions from the spreadsheet. ### `reorder_worksheets(worksheets)` **Description**: Reorders the worksheets within the spreadsheet. ### `share(email, perm_type, role, ...)` **Description**: Shares the spreadsheet with specified users or groups. ### `transfer_ownership(email, perm_type, role, ...)` **Description**: Transfers ownership of the spreadsheet to another user. ### Properties: - `sheet1`: Accesses the first worksheet. - `timezone`: Gets or sets the spreadsheet's timezone. - `title`: Gets or sets the spreadsheet's title. ``` -------------------------------- ### Read Sheet Data into Pandas DataFrame Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Converts all records from a worksheet into a pandas DataFrame. Assumes the first row contains headers. Requires pandas to be installed. ```python import pandas as pd dataframe = pd.DataFrame(worksheet.get_all_records()) ``` -------------------------------- ### Get Cell Value in A1 Notation Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieves a Cell object for a given cell label. The value render option can be specified to control how the value is returned. ```python >>> worksheet.acell('A1') ``` -------------------------------- ### Open Spreadsheet with API Key Source: https://docs.gspread.org/en/v6.2.1/_sources/oauth2.rst.txt Use this code to open a public spreadsheet using an API key. Ensure you have obtained and replaced '' with your actual API key and '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' with the spreadsheet's key. ```python import gspread gc = gspread.api_key("") sh = gc.open_by_key("1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms") print(sh.sheet1.get('A1')) ``` -------------------------------- ### Get Cell Formula by Row and Column Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves the formula of a cell using its row and column coordinates, by specifying `value_render_option='FORMULA'`. Useful for programmatic formula retrieval. ```python cell = worksheet.cell(1, 2, value_render_option='FORMULA').value ``` -------------------------------- ### gspread.Client Methods (Auth) Source: https://docs.gspread.org/en/v6.2.1/genindex.html Authentication methods available on the gspread.Client object. ```APIDOC ## Client Authentication Methods ### `oauth()` **Description**: Authenticates using OAuth credentials. ### `service_account(filename)` **Description**: Authenticates using a service account key file. ``` -------------------------------- ### gspread.auth.authorize Source: https://docs.gspread.org/en/v6.2.1/api/auth.html Logs into the Google API using OAuth2 credentials. This is a helper function that instantiates a client using http_client. ```APIDOC ## POST /api/auth/authorize ### Description Logs into the Google API using OAuth2 credentials. This is a helper function that instantiates a client using http_client. ### Method POST ### Endpoint /api/auth/authorize ### Parameters #### Request Body - **credentials** (google.auth.credentials.Credentials) - Required - The OAuth2 credentials. - **http_client** (gspread.http_client.HTTPClient) - Optional - A factory function that returns a client class. Defaults to `gspread.http_client.HTTPClient`. - **session** (requests.Session | None) - Optional - A custom requests.Session object. If provided, credentials should be None. ``` -------------------------------- ### Get All Records from Worksheet Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieves all data from the worksheet as a list of dictionaries. The first row is used as keys for the dictionaries. Cell values are automatically numericised unless ignored. ```python >>> worksheet.get_all_records() [ {"A1": "A6", "B2": "B7", "C3": "C8"}, {"A1": "A11", "B2": "B12", "C3": "C13"} ] ``` -------------------------------- ### OAuth Authentication from Dictionary Credentials Source: https://docs.gspread.org/en/v6.2.1/oauth2.html Authenticate by providing credentials directly as a Python dictionary. This avoids storing files and is useful for password managers. ```python import gspread credentials = { "installed": { "client_id": "12345678901234567890abcdefghijklmn.apps.googleusercontent.com", "project_id": "my-project1234", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "...": "..." } } gc, authorized_user = gspread.oauth_from_dict(credentials) sh = gc.open("Example spreadsheet") print(sh.sheet1.get('A1')) ``` -------------------------------- ### Get Unformatted Values Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieve values from a specified range without applying any formatting. This is useful for obtaining raw data, such as numbers as numbers instead of formatted strings. ```python worksheet.get('A2:B4', value_render_option=ValueRenderOption.unformatted) ``` -------------------------------- ### HTTPClient.get_file_drive_metadata Source: https://docs.gspread.org/en/v6.2.1/api/http_client.html Get the metadata from the Drive API for a specific file. This method is primarily used to retrieve creation and update times of a file, which are only accessible via the Drive API. ```APIDOC ## HTTPClient.get_file_drive_metadata ### Description Get the metadata from the Drive API for a specific file. This method is mainly here to retrieve the create/update time of a file (these metadata are only accessible from the Drive API). ### Method GET ### Endpoint `files/{id}` ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the file. ### Response #### Success Response (200) - **drive_metadata** (Any) - The metadata from the Drive API. ### Response Example ```json { "drive_metadata": { "id": "12345abcde", "name": "My Spreadsheet", "createdTime": "2023-01-01T10:00:00Z", "modifiedTime": "2023-01-01T12:00:00Z" } } ``` ``` -------------------------------- ### Client.copy() Source: https://docs.gspread.org/en/v6.2.1/api/client.html Copies an existing spreadsheet. This method can also copy permissions, specify a folder for the new spreadsheet, and copy comments. ```APIDOC ## Client.copy() ### Description Copies a spreadsheet. ### Method `copy(_file_id : str_, _title : str | None = None_, _copy_permissions : bool = False_, _folder_id : str | None = None_, _copy_comments : bool = True_) → Spreadsheet` ### Parameters #### Path Parameters - **file_id** (str) - Required - A key of a spreadsheet to copy. - **title** (str) - Optional - A title for the new spreadsheet. - **copy_permissions** (bool) - Optional - If True, copy permissions from the original spreadsheet to the new spreadsheet. Defaults to False. - **folder_id** (str) - Optional - Id of the folder where we want to save the spreadsheet. - **copy_comments** (bool) - Optional - If True, copy the comments from the original spreadsheet to the new spreadsheet. Defaults to True. ### Returns - `Spreadsheet` instance. ### Notes - New in version 3.1.0. - If using custom credentials without the Drive scope, `https://www.googleapis.com/auth/drive` must be added to your OAuth scope. ### Example ```python scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] ``` ``` -------------------------------- ### oauth() Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Initializes gspread using OAuth 2.0 credentials. This is typically used for user-authorized access to Google Sheets. ```APIDOC ## oauth() ### Description Initializes gspread using OAuth 2.0 credentials. ### Method `oauth()` ### Parameters This function typically takes credentials as an argument, but specific parameter details are not provided in the source. ``` -------------------------------- ### Get All Worksheet Values as List of Dictionaries Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Fetches all values from a worksheet and returns them as a list of dictionaries, using the first row as headers. Ideal for structured data access. ```python list_of_dicts = worksheet.get_all_records() ``` -------------------------------- ### Get Cell Value by A1 Notation Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves the value of a cell using its A1 notation (e.g., 'B1'). This is the standard way to reference cells in Google Sheets. ```python val = worksheet.acell('B1').value ``` -------------------------------- ### gspread.utils.StrEnum Class Source: https://docs.gspread.org/en/v6.2.1/genindex.html Base class for string enumerations in gspread.utils. ```APIDOC ## StrEnum Class **Description**: A base class for creating enumerations with string values. ``` -------------------------------- ### OAuth Authentication with Custom Credential Paths Source: https://docs.gspread.org/en/v6.2.1/oauth2.html Specify custom file paths for credentials.json and authorized_user.json if they are not in the default location. ```python gc = gspread.oauth( credentials_filename='path/to/the/credentials.json', authorized_user_filename='path/to/the/authorized_user.json' ) ``` -------------------------------- ### Check for Full A1 Notation Source: https://docs.gspread.org/en/v6.2.1/api/utils.html Determines if a given range name is a full A1 notation, meaning it includes both the start and end cells (e.g., 'A1:B2'). ```python >>> is_full_a1_notation("A1:B2") True ``` ```python >>> is_full_a1_notation("A1:B") False ``` -------------------------------- ### Batch Get Values from Worksheet Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Reads values from multiple specified ranges and cells within a worksheet. Useful for fetching data from distinct areas of a sheet in a single request. ```python worksheet.batch_get(['A1:B2', 'F12']) ``` -------------------------------- ### OAuth with Custom Credential Paths Source: https://docs.gspread.org/en/v6.2.1/api/top-level.html Specify alternative file paths for your credentials and authorized user JSON files if they are not in the default locations. ```python gc = gspread.oauth( credentials_filename='/alternative/path/credentials.json', authorized_user_filename='/alternative/path/authorized_user.json', ) ``` -------------------------------- ### gspread.HTTPClient Methods Source: https://docs.gspread.org/en/v6.2.1/genindex.html Methods available on the gspread.HTTPClient object for making HTTP requests. ```APIDOC ## HTTPClient Methods ### `remove_permission(entity, role)` **Description**: Removes a permission for a given entity and role. ### `set_timeout(timeout)` **Description**: Sets the timeout for HTTP requests. ### `spreadsheets_get()` **Description**: Retrieves a list of spreadsheets. ### `spreadsheets_sheets_copy_to(spreadsheet_id, sheet_id)` **Description**: Copies a sheet to another spreadsheet. ``` -------------------------------- ### Get Unformatted Cell Range Values Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves unformatted numerical values from a range of cells using `ValueRenderOption.unformatted`. This is useful for calculations and data processing, ignoring display formatting. ```python from gspread.utils import ValueRenderOption worksheet.get("A1:B2", value_render_option=ValueRenderOption.unformatted) ``` -------------------------------- ### Get Cells from a Range Source: https://docs.gspread.org/en/v6.2.1/api/models/worksheet.html Retrieves a list of Cell objects from a specified range using either A1 notation or numeric boundaries. Can also fetch all cells or use named ranges. ```python >>> # Using A1 notation >>> worksheet.range('A1:B7') [, ...] >>> # Same with numeric boundaries >>> worksheet.range(1, 1, 7, 2) [, ...] >>> # Named ranges work as well >>> worksheet.range('NamedRange') [, ...] >>> # All values in a single API call >>> worksheet.range() [, ...] ``` -------------------------------- ### HTTPClient list_permissions Method Source: https://docs.gspread.org/en/v6.2.1/api/http_client.html Lists all permissions for a spreadsheet. This method helps in auditing and managing who has access to the document. ```python list_permissions(_id : str_) → Any ``` -------------------------------- ### HTTPClient fetch_sheet_metadata Method Source: https://docs.gspread.org/en/v6.2.1/api/http_client.html Retrieve spreadsheet metadata without fetching cell data. This is useful for getting information like creation or update times. Optional HTTP parameters can be provided. ```python fetch_sheet_metadata(_id : str_, _params : MutableMapping[str, str | int | bool | float | List[str] | None] | None = None_) → Mapping[str, Any] ``` -------------------------------- ### open Source: https://docs.gspread.org/en/v6.2.1/api/client.html Opens a specific spreadsheet by its title, optionally filtering by a parent folder ID. ```APIDOC ## open ### Description Opens a spreadsheet. ### Method open ### Parameters #### Path Parameters - **title** (str) - A title of a spreadsheet. - **folder_id** (str) - Optional - If specified can be used to filter spreadsheets by parent folder ID. ### Response #### Success Response (Spreadsheet) a `Spreadsheet` instance. If there’s more than one spreadsheet with same title the first one will be opened. ### Raises **gspread.SpreadsheetNotFound** – if no spreadsheet with specified title is found. ### Request Example ```python >>> gc.open('My fancy spreadsheet') ``` ``` -------------------------------- ### Get Formatted Cell Range Values Source: https://docs.gspread.org/en/v6.2.1/_sources/user-guide.rst.txt Retrieves formatted values from a range of cells (e.g., 'A1:B2'). The output reflects how the data is displayed in the sheet, including currency symbols. ```python worksheet.get("A1:B2") ``` -------------------------------- ### Specify Custom Credential File Paths Source: https://docs.gspread.org/en/v6.2.1/_sources/oauth2.rst.txt If you prefer to store your credentials in a location other than the default, you can specify the paths to the credentials and authorized user JSON files. ```python gc = gspread.oauth( credentials_filename='path/to/the/credentials.json', authorized_user_filename='path/to/the/authorized_user.json' ) ``` -------------------------------- ### HTTP Client Classes Source: https://docs.gspread.org/en/v6.2.1/api/index.html Classes for handling HTTP requests with backoff strategies. ```APIDOC ## HTTP Client Classes ### `HTTPClient` A basic HTTP client for making requests. ### `BackOffHTTPClient` An HTTP client that implements backoff strategies for retrying failed requests. ``` -------------------------------- ### to_records Source: https://docs.gspread.org/en/v6.2.1/api/utils.html Builds a list of dictionaries from a list of headers and a matrix of values. ```APIDOC ## to_records ### Description Builds a list of dictionaries from a list of headers and a matrix of values. Each dictionary uses the headers as keys and the corresponding values from the matrix. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **headers** (_Iterable[Any]_): The headers to use as keys for the dictionaries. Defaults to an empty list. * **values** (_Iterable[Iterable[Any]]_): A matrix of values. Defaults to a list containing an empty list. ### Response #### Success Response (200) - **records** (List[Dict[str, str | int | float]]) - A list of dictionaries, where each dictionary represents a row of data. ### Request Example ```python >>> to_records(["name", "City"], [["Spiderman", "NY"], ["Batman", "Gotham"]]) [ { "Name": "Spiderman", "City": "NY", }, { "Name": "Batman", "City": "Gotham", }, ] ``` ```