### create usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Example of creating a spreadsheet and printing its URL using the spreadsheet id. ```python ss = await c.create("Test Spreadsheet") print("https://docs.google.com/spreadsheets/d/{0}".format(ss.id)) ``` -------------------------------- ### Read values with get and get_values Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Usage examples for get and get_values. get_values returns a list of lists; get returns a ValueRange. The formula option retrieves formulas instead of formatted values. ```python rows = await ws.get_values() await ws.get("A1"); await ws.get("A1:B2") formulas = await ws.get_values(value_render_option=gspread.utils.ValueRenderOption.formula) ``` -------------------------------- ### Transfer ownership example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to transfer ownership using a permission ID. ```python await ss.transfer_ownership("perm-12345") ``` -------------------------------- ### gspread_asyncio usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/docs/api.rst Complete example of using gspread_asyncio: set up a credentials callback, create a ClientManager, authorize, create a spreadsheet, grant write permission, add a worksheet, and update cells. Requires Python >= 3.11 and a service account JSON file. Run with asyncio debug mode enabled. ```python import asyncio import gspread_asyncio # from google-auth package from google.oauth2.service_account import Credentials # First, set up a callback function that fetches our credentials off the disk. # gspread_asyncio needs this to re-authenticate when credentials expire. def get_creds(): # To obtain a service account JSON file, follow these steps: # https://gspread.readthedocs.io/en/latest/oauth2.html#for-bots-using-service-account creds = Credentials.from_service_account_file("serviceacct_spreadsheet.json") scoped = creds.with_scopes([ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive", ]) return scoped # Create a ClientManager object which # will give us access to the Spreadsheet API. cm = gspread_asyncio.ClientManager(get_creds) # Here's an example of how you use the API: async def example(cm): # Always authorize first. # If you have a long-running program call authorize() repeatedly. c = await cm.authorize() ss = await c.create("Test Spreadsheet") print("Spreadsheet URL: https://docs.google.com/spreadsheets/d/{0}".format(ss.id)) print("Open the URL in your browser to see gspread_asyncio in action!") # Allow anyone with the URL to write to this spreadsheet. await c.insert_permission(ss.id, None, perm_type="anyone", role="writer") # Create a new spreadsheet but also grab a reference to the default one. ws = await ss.add_worksheet("My Test Worksheet", 10, 5) zero_ws = await ss.get_worksheet(0) # Write some stuff to both spreadsheets. for row in range(1, 11): for col in range(1, 6): val = "{0}/{1}".format(row, col) await ws.update_cell(row, col, val + " ws") await zero_ws.update_cell(row, col, val + " zero ws") print("All done!") # Turn on debugging if you're new to asyncio! asyncio.run(example(cm), debug=True) ``` -------------------------------- ### open_by_key usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Shows how to open a spreadsheet by its key using the open_by_key method. ```python ss = await c.open_by_key("1dv5...spreadsheet-id") ``` -------------------------------- ### copy usage examples Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Examples of using the copy method. The first copies with permissions and a new title. The second uses nowait=True for a fire-and-forget copy that returns a Task. ```python copy = await c.copy("1abc123", title="Backup 2024", copy_permissions=True) # non-trivial option: fire-and-forget copy task = await c.copy("1abc123", title="Async copy", copy_comments=False, nowait=True) ``` -------------------------------- ### Share spreadsheet example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to share a spreadsheet with a user by email, setting permission type to 'user' and role to 'writer'. ```python await ss.share('otto@example.com', perm_type='user', role='writer') ``` -------------------------------- ### get and get_values method signatures Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Method signatures for get and get_values. get returns a ValueRange; get_values returns a list of lists. pad_values defaults to False for get and True for get_values. ```python async def get( self, range_name: str | None = None, major_dimension: str | None = None, value_render_option: gspread.utils.ValueRenderOption = None, date_time_render_option: gspread.utils.DateTimeOption = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = False, return_type: gspread.utils.GridRangeType = gspread.utils.GridRangeType.ValueRange, ): ``` ```python async def get_values( self, range_name: str | None = None, major_dimension: str | None = None, value_render_option: gspread.utils.ValueRenderOption = None, date_time_render_option: gspread.utils.DateTimeOption = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = True, return_type: gspread.utils.GridRangeType = gspread.utils.GridRangeType.ListOfLists, ) -> list[list]: ``` -------------------------------- ### open_by_url usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Shows how to open a spreadsheet by its URL using the open_by_url method. ```python ss = await c.open_by_url("https://docs.google.com/spreadsheets/d/1abc123/edit") ``` -------------------------------- ### insert_permission usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Example from the README showing how to allow anyone with the URL to write by calling insert_permission with perm_type='anyone' and role='writer'. ```python # Allow anyone with the URL to write (README example) await c.insert_permission(ss.id, None, perm_type="anyone", role="writer") ``` -------------------------------- ### add_worksheet usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to add_worksheet with title, rows, and columns. Use to create a new worksheet tab. ```python ws = await ss.add_worksheet("My Test Worksheet", 10, 5) ``` -------------------------------- ### get_worksheet usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to get_worksheet with index 0. Use this to obtain the first worksheet before performing operations. ```python first = await ss.get_worksheet(0) # always call before working on a sheet ``` -------------------------------- ### get Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Asynchronously retrieves values from a range with various options. ```APIDOC ## get ### Description Asynchronously retrieves values from a range with various options. ### Method async ### Signature ```python async def get( self, range_name: str | None = None, major_dimension: str | None = None, value_render_option: gspread.utils.ValueRenderOption = None, date_time_render_option: gspread.utils.DateTimeOption = None, combine_merged_cells: bool = False, maintain_size: bool = False, pad_values: bool = False, return_type: gspread.utils.GridRangeType = gspread.utils.GridRangeType.ValueRange, ): ``` ### Parameters - **range_name** (str | None) - Optional - A1 or named range. Defaults to None (used). - **major_dimension** (str | None) - Optional - `ROWS` or `COLUMNS`. - **value_render_option** (gspread.utils.ValueRenderOption) - Optional - `FORMATTED_VALUE`, `UNFORMATTED_VALUE`, or `FORMULA`. - **date_time_render_option** (gspread.utils.DateTimeOption) - Optional - Ignored when formatted. - **combine_merged_cells** (bool) - Optional - Merged cells take top-left value (adds one API request). Defaults to False. - **maintain_size** (bool) - Optional - Maintain size. Defaults to False. - **pad_values** (bool) - Optional - Pad values. Defaults to False. - **return_type** (gspread.utils.GridRangeType) - Optional - `ValueRange` or `ListOfLists`. Defaults to `ValueRange`. ### Returns Response - **gspread.worksheet.ValueRange** - The value range object. ### Example ```python await ws.get("A1") await ws.get("A1:B2") ``` ``` -------------------------------- ### worksheet usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to worksheet with a title. Use to fetch a worksheet by its human-readable name. ```python ws = await ss.worksheet("Sheet1") ``` -------------------------------- ### Import and basic usage of gspread_asyncio Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/README.md Shows the primary import and usage pattern for gspread_asyncio: create a ClientManager with a credentials callback, then await authorize() to get a Client, open a spreadsheet by key, and access a worksheet. Also lists the legacy class names that remain available for backward compatibility. ```python import gspread_asyncio cm = gspread_asyncio.ClientManager(get_creds) # entry point c = await cm.authorize() # -> gspread_asyncio.Client ss = await c.open_by_key("1abc...") # -> gspread_asyncio.Spreadsheet ws = await ss.worksheet("Sheet1") # -> gspread_asyncio.Worksheet # legacy names still work from gspread_asyncio import ( AsyncioGspreadClientManager, AsyncioGspreadClient, AsyncioGspreadSpreadsheet, AsyncioGspreadWorksheet, ) ``` -------------------------------- ### values_get example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Fetches values from a range using the raw pass-through method and prints the returned values. ```python resp = await ss.values_get("A1:B2") print(resp["values"]) ``` -------------------------------- ### Export spreadsheet as Excel with gspread_asyncio Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to export the spreadsheet as an Excel file. The result is stored in the variable data. ```python data = await ss.export(gspread.utils.ExportFormat.EXCEL) ``` -------------------------------- ### export usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Exports a spreadsheet as CSV and writes the bytes to a file. Uses ExportFormat.CSV. ```python from gspread.utils import ExportFormat csv_bytes = await c.export("1abc123", format=ExportFormat.CSV) open("backup.csv", "wb").write(csv_bytes) ``` -------------------------------- ### duplicate_sheet usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to duplicate_sheet with source_sheet_id and new_sheet_name. Use to create a copy of an existing worksheet. ```python dup = await ss.duplicate_sheet(source_sheet_id=ws.id, new_sheet_name="Copy") ``` -------------------------------- ### open usage examples Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Shows two calls to the open method. The first call without folder_id is cached after the first call; the second call with folder_id always fetches because the cache is bypassed. ```python ss = await c.open("Monthly Report") # cached after first call ss = await c.open("Monthly Report", folder_id="12345") # always fetches ``` -------------------------------- ### insert_row / insert_rows / insert_cols / add_rows / add_cols / resize / delete_* with example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Insert rows/columns, add rows/columns, resize, and delete rows/columns/dimensions. `insert_*` places `values` at `index`/`row`/`col` (default 1) with `value_input_option=ValueInputOption.raw` and `inherit_from_before=False` (must stay `False` at the top/left edge, `True` at the bottom/right). `insert_rows` uses `api_call_count=2`. `add_rows(rows)`/`add_cols(cols)`; `resize(rows=None, cols=None)` requires at least one. Deletes: `delete_rows(index, end_index=None)` is 1-based; `delete_columns(start_index, end_index=None)` and `delete_dimension(dimension, start_index, end_index=None)` are 0-based (`dimension` = `Dimension.rows`/`cols`). Returns delegated responses. ```python @_nowait async def insert_row( self, values: list, index: int = 1, value_input_option: gspread.utils.ValueInputOption = gspread.utils.ValueInputOption.raw, inherit_from_before: bool = False, ): # line 2498 @_nowait async def insert_rows( self, values: list[list], row: int = 1, value_input_option: gspread.utils.ValueInputOption = gspread.utils.ValueInputOption.raw, inherit_from_before: bool = False, ): # line 2543 @_nowait async def insert_cols( self, values: list[list], col: int = 1, value_input_option: gspread.utils.ValueInputOption = gspread.utils.ValueInputOption.raw, inherit_from_before: bool = False, ): # line 2408 @_nowait async def add_rows(self, rows: int): # line 1357 @_nowait async def add_cols(self, cols: int): # line 1264 @_nowait async def resize(self, rows: int | None = None, cols: int | None = None): # line 2696 @_nowait async def delete_rows(self, index: int, end_index: int | None = None): # line 1912 @_nowait async def delete_columns(self, start_index: int, end_index: int | None = None): # line 1854 @_nowait async def delete_dimension( self, dimension: str, start_index: int, end_index: int | None = None ): # line 1871 ``` ```python await ws.insert_row(["x", "y"], index=1) await ws.delete_rows(3) ``` -------------------------------- ### get_all_records usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Calls get_all_records with empty2zero=True to convert empty cells to zero. ```python records = await ws.get_all_records(empty2zero=True) ``` -------------------------------- ### import_csv usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Imports CSV content into the spreadsheet with the given file_id. ```python await c.import_csv("1abc123", "a,b,c\n1,2,3\n") ``` -------------------------------- ### Iterate over all spreadsheets with openall Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Example usage of openall: iterates over all wrapped spreadsheets and prints each spreadsheet's title and id. ```python for ss in await c.openall(): print(ss.title, ss.id) ``` -------------------------------- ### Insert, update, and clear notes Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Example usage of insert_note, update_notes, and clear_note. The notes dict maps A1 coordinates to text. ```python await ws.insert_note("D7", "review this") await ws.update_notes({"D7": "updated note", "GH42": "far away"}) await ws.clear_note("D7") ``` -------------------------------- ### batch_update / batch_get / batch_clear / batch_format signatures and usage Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Shows the async signatures for batch_update, batch_get, batch_clear, and batch_format, then usage examples. batch_update accepts data as a list of {"range", "values"} objects; named ranges are allowed and None values are skipped. batch_get returns a list; batch_clear and batch_format delegate to the underlying API. batch_format takes a list of {"range", "format"} dictionaries per CellFormat. ```python @_nowait async def batch_update( self, data, raw=True, value_input_option: gspread.utils.ValueInputOption = None, include_values_in_response=None, response_value_render_option: gspread.utils.ValueRenderOption = None, response_date_time_render_option: gspread.utils.DateTimeOption = None, ): # line 1559 async def batch_get( self, ranges: list[str], major_dimension: str | None = None, value_render_option: gspread.utils.ValueRenderOption = None, date_time_render_option: gspread.utils.DateTimeOption = None, ) -> list: # line 1519 @_nowait async def batch_clear(self, ranges: list[str]): # line 1459 @_nowait async def batch_format(self, formats: list[dict]): # line 1474 ``` ```python await ws.batch_update([{"range": "A1:B1", "values": [["42", "43"]]}, {"range": "my_range", "values": [["44", "45"]]}]) await ws.batch_format([{"range": "A1:C1", "format": {"textFormat": {"bold": True}}}]) ``` -------------------------------- ### reorder_worksheets signature and usage Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md The method signature shows the decorator and parameters for reordering worksheets. The usage example fetches all worksheets and passes them in reversed order to reorder_worksheets. ```python @_nowait async def reorder_worksheets( self, worksheets_in_desired_order: "Iterable[Worksheet]" ): ``` ```python wss = await ss.worksheets() await ss.reorder_worksheets(reversed(wss)) ``` -------------------------------- ### update / update_cell / update_acell / update_cells signatures and usage Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Shows the async signatures for update, update_cell, update_acell, and update_cells, then usage examples. update_cell and update_acell return an A1 coordinate string; others return delegated responses. With nowait=True all return a scheduled task. The try/except demonstrates that 400-range misuse errors are re-raised as gspread.exceptions.APIError. ```python @_nowait async def update( self, values: list[list], range_name: str | None = None, raw=True, major_dimension: str | None = None, value_input_option: gspread.utils.ValueInputOption = None, include_values_in_response=None, response_value_render_option: gspread.utils.ValueRenderOption = None, response_date_time_render_option: gspread.utils.DateTimeOption = None, ): # line 2909 @_nowait async def update_cell(self, row: int, col: int, value): # line 2976 @_nowait async def update_acell(self, label: str, value): # line 2962 @_nowait async def update_cells( self, cell_list: list[gspread.Cell], value_input_option: gspread.utils.ValueInputOption = gspread.utils.ValueInputOption.raw, ): # line 2988 ``` ```python await ws.update_cell(2, 3, "42") # single cell await ws.update([["a", "b"], ["c", "d"]], range_name="A1:B2") await ws.update_acell("A1", "hello") # A1 label # 400-range misuse errors are re-raised (see errors.md): try: await ws.update_cell(0, 0, "x") except gspread.exceptions.APIError as e: print("HTTP", e.response.status_code) ``` -------------------------------- ### Read cell and range values Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Usage examples for reading a single cell and a range of cells. cell returns a gspread.Cell; range returns a list of gspread.Cell. ```python cell = await ws.cell(2, 1) # -> gspread.Cell cells = await ws.range("A1:B2") ``` -------------------------------- ### Update locale, timezone, and title usage Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example usage of the update methods. update_locale accepts ISO 639-1 or combined language/country codes, update_timezone accepts CLDR format or custom offsets, and update_title sets a new title. ```python await ss.update_locale("en_US") await ss.update_timezone("America/New_York") await ss.update_title("Renamed") ``` -------------------------------- ### Check credential expiry after authorize Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Example usage of the expiry property after obtaining a client via authorize(). Prints the credential expiry if not None. ```python c = await cm.authorize() if c.expiry is not None: print("credentials valid until", c.expiry.isoformat()) ``` -------------------------------- ### worksheets usage with exclude_hidden Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example call to worksheets with exclude_hidden=True. Use to get only visible worksheets. ```python visible = await ss.worksheets(exclude_hidden=True) ``` -------------------------------- ### Basic usage of authorize with ClientManager Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client-manager.md Shows how to create a ClientManager with a credentials function, call authorize, and then use the client. The authorize call is required before any work and is cheap to call again due to caching. ```python import asyncio, gspread_asyncio from google.oauth2.service_account import Credentials def get_creds(): creds = Credentials.from_service_account_file("serviceacct.json") return creds.with_scopes([ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive", ]) async def main(): cm = gspread_asyncio.ClientManager(get_creds) client = await cm.authorize() # must be called before any work await client.open_by_key("1abc123") # reuse: authorize() again is cheap asyncio.run(main()) ``` -------------------------------- ### login Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Raises NotImplementedError unconditionally. Use ClientManager.authorize() to create a gspread client. ```APIDOC ## login ### Description Raises `NotImplementedError("Use ClientManager.authorize() to create a gspread client")` unconditionally. ### Method login ### Signature ```python async def login(self): ``` ### Raises - `NotImplementedError` - Always raised. ``` -------------------------------- ### ClientManager.__init__ signature Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client-manager.md Constructor for ClientManager. Requires a thread-safe, zero-argument credentials_fn. Defaults: gspread_delay=1.1 (recommended for Google's rate limit), reauth_interval=45 minutes (stored as seconds), cell_flush_delay=5.0 (currently unused), gspread_timeout=None (passed to gspread.Client.set_timeout()). ```python def __init__( self, credentials_fn: "Callable[[], CredentialTypes]", gspread_delay: float = 1.1, reauth_interval: int = 45, cell_flush_delay: float = 5.0, gspread_timeout: "float | tuple[float, float] | None" = None, ): ``` -------------------------------- ### ClientManager.__init__ Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client-manager.md Constructor for the ClientManager class. Initializes the manager with a credentials function and optional configuration parameters for rate limiting, reauthentication, and timeouts. ```APIDOC ## ClientManager.__init__ ### Description Initializes a new ClientManager instance. This is the entry point of the library and should be kept for the duration of the program. ### Method Constructor ### Signature ```python def __init__( self, credentials_fn: "Callable[[], CredentialTypes]", gspread_delay: float = 1.1, reauth_interval: int = 45, cell_flush_delay: float = 5.0, gspread_timeout: "float | tuple[float, float] | None" = None, ): ``` ### Parameters - **credentials_fn** (Callable[[], CredentialTypes]) - Required - Non-async, zero-argument, thread-safe callable returning credential objects. Called via asyncio.to_thread whenever new credentials are needed. - **gspread_delay** (float) - Optional, default 1.1 - Minimum seconds between Google API calls (client-side rate limiting). 1.1s is recommended because Google's rate limit is 1 call/sec with jitter. - **reauth_interval** (int) - Optional, default 45 - Credential re-fetch interval in minutes. Stored internally as reauth_interval * 60 seconds. - **cell_flush_delay** (float) - Optional, default 5.0 - Stored as self.cell_flush_delay; currently unused. - **gspread_timeout** (float | tuple[float, float] | None) - Optional, default None - Passed to gspread.Client.set_timeout() at authorization time. Added in v3. ### Attributes After initialization, the instance exposes the following user-facing attributes: - `credentials_fn` - The credentials function. - `gspread_delay` - The rate limit delay. - `cell_flush_delay` - The cell flush delay. - `gspread_timeout` - The timeout value. - `reauth_interval` - The reauth interval in seconds. - `auth_time` (float | None) - Time of last authentication. - `last_call` (float | None) - Time of last API call. - Private caches: `_client_cache` (dict[float, Client]), `auth_lock` (asyncio.Lock), `call_lock` (asyncio.Lock), `_cell_flusher_active` (bool). ``` -------------------------------- ### values_get Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Raw Sheets API v4 pass-through method to get values from a range. ```APIDOC ## values_get ### Description Wraps the low-level gspread REST pass-through method for `values/`. Returns the Google API response body verbatim. ### Method async def values_get(self, range: str, params: dict | None = None) -> dict ### Parameters - **range** (str) - Required - A1 notation range. - **params** (dict | None) - Optional - Google API query parameters. ### Returns dict - `values/` response ### Example ```python resp = await ss.values_get("A1:B2") print(resp["values"]) ``` ### Source Line 1133. ``` -------------------------------- ### Client constructor signature Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Constructor signature for Client. Instances must be obtained from ClientManager.authorize(); the constructor is not for application use. ```python def __init__(self, cm: ClientManager, gc: gspread.Client): ``` -------------------------------- ### Object model and data flow diagram Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/README.md ASCII diagram showing the data flow from credentials_fn through ClientManager, Client, Spreadsheet, and Worksheet, ending at ClientManager._call() with retry logic. The diagram illustrates the async facade pattern and the extension points. ```text credentials_fn (callable) │ ▼ ClientManager (owns auth lock, call lock, rate-limit delay, credential cache) │ authorize() → gspread.authorize(credentials_fn()) → set_timeout() ▼ Client (wraps gspread.Client; caches wrapped Spreadsheet objects) │ open / open_by_key / create / copy ... ▼ Spreadsheet (wraps gspread.Spreadsheet; caches wrapped Worksheet objects) │ worksheet / get_worksheet / add_worksheet ... ▼ Worksheet (wraps gspread.Worksheet; no child caches) │ update / get / append_row / ... ▼ ClientManager._call() → delay() → before_gspread_call() → asyncio.to_thread(gspread method) │ ▲ error handlers retry forever (5xx, 429, socket errors) ``` -------------------------------- ### row_values usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Calls row_values(1) on a worksheet to retrieve the values of the first row. ```python await ws.row_values(1) ``` -------------------------------- ### create Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Asynchronously creates a new spreadsheet with the given title, optionally in a specified folder. Returns a wrapped Spreadsheet object. ```APIDOC ## create ### Description Asynchronously creates a new spreadsheet with the given title, optionally in a specified folder. Returns a wrapped `Spreadsheet` object. ### Method `async def create` ### Signature ```python async def create(self, title: str, folder_id: str | None = None) -> "Spreadsheet": ``` ### Parameters - `title` (str) - Required - Human-readable name of the new spreadsheet - `folder_id` (str | None) - Optional - Id of the folder to save the spreadsheet in ### Returns - Wrapped `Spreadsheet` for the newly created spreadsheet. ### Example ```python ss = await c.create("Test Spreadsheet") print("https://docs.google.com/spreadsheets/d/{0}".format(ss.id)) ``` ``` -------------------------------- ### values_batch_get Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Raw Sheets API v4 pass-through method to batch get values from multiple ranges. ```APIDOC ## values_batch_get ### Description Wraps the low-level gspread REST pass-through method for `values:batchGet`. Returns the Google API response body verbatim. ### Method async def values_batch_get(self, ranges: list[str], params: dict | None = None) -> dict ### Parameters - **ranges** (list[str]) - Required - List of A1 notation ranges. - **params** (dict | None) - Optional - Google API query parameters. ### Returns dict - `values:batchGet` response ### Source Line 1081. ``` -------------------------------- ### expand and update_tab_color usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Calls expand on cell A1 and updates the tab color to #336699. ```python await ws.expand("A1") await ws.update_tab_color("#336699") ``` -------------------------------- ### login method signature Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Declares the async login method. It unconditionally raises NotImplementedError with the message 'Use ClientManager.authorize() to create a gspread client'. ```python async def login(self): ``` -------------------------------- ### findall usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Calls findall with a compiled regex pattern and case_sensitive=False to find all cells matching '^err'. ```python await ws.findall(re.compile(r"^err"), case_sensitive=False) ``` -------------------------------- ### del_spreadsheet usage example Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Shows creating a temporary sheet and then deleting it with del_spreadsheet, which purges cache entries for the spreadsheet id. ```python await c.create("temporary sheet") # ... work ... await c.del_spreadsheet(ss.id) # cache entries for ss.id are purged ``` -------------------------------- ### authorize Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client-manager.md Documentation for the authorize method of the gspread_asyncio ClientManager class. ```APIDOC ## authorize ### Description Asynchronously authenticates and returns a ready-to-use asyncio wrapper for `gspread.Client`. It serializes concurrent callers with an internal lock and re-authenticates only when the cached credentials are stale, otherwise returning the cached client. ### Method async def authorize(self) -> "Client" ### Parameters (none) ### Returns - **gspread_asyncio.Client** — a ready-to-use asyncio wrapper for `gspread.Client`. ### Behavior - Wrapped in `self.auth_lock` (serializes concurrent callers). - Delegates to the private `_authorize()` which (re)authenticates only when `auth_time` is `None` or `auth_time + reauth_interval < now`; otherwise returns the cached client from `_client_cache` keyed by the auth timestamp. - Fresh authentication runs `credentials_fn()`, `gspread.authorize(creds)`, and `gc.set_timeout(self.gspread_timeout)` — each inside `asyncio.to_thread`. - The replaced cache entry is evicted. ### Source - line 242 (`_authorize` at line 259). ### Example ```python import asyncio, gspread_asyncio from google.oauth2.service_account import Credentials def get_creds(): creds = Credentials.from_service_account_file("serviceacct.json") return creds.with_scopes([ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive", ]) async def main(): cm = gspread_asyncio.ClientManager(get_creds) client = await cm.authorize() # must be called before any work await client.open_by_key("1abc123") # reuse: authorize() again is cheap asyncio.run(main()) ``` Calling repeatedly in a loop is safe and cheap — between reauth intervals `authorize()` only performs dictionary lookups under the lock. ``` -------------------------------- ### expand / get_note / get_notes / get_tab_color signatures Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Signatures for expand, get_note, get_notes, and get_tab_color. expand grows from non-empty cells with direction table/down/right; get_note returns note text or empty string; get_notes returns a list of lists with optional default_empty_value and grid_range; get_tab_color returns hex color or None. ```python async def expand( self, top_left_range_name: str = "A1", direction: gspread.utils.TableDirection = gspread.utils.TableDirection.table, ) -> list[list[str]]: # line 2189 async def get_note(self, cell: str) -> str: # line 2214 async def get_notes( self, default_empty_value: str | None = "", grid_range: str | None = None, ) -> list[list[str]]: # line 2225 async def get_tab_color(self) -> str | None: # line 3052 ``` -------------------------------- ### del_worksheet and del_worksheet_by_id usage Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example calls to delete a worksheet by wrapper and by gid. The by_id variant works without a wrapper. ```python await ss.del_worksheet(ws) await ss.del_worksheet_by_id(1234) # works even without a wrapper ``` -------------------------------- ### Formatting, validation, and visibility method signatures Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Method signatures for formatting, auto-resizing, validation, tab color, and gridlines. The format dict uses the same shape as batch_format. add_validation accepts condition_type like ValidationConditionType.number_greater with values like [10]; strict rejects invalid input and showCustomUi shows a dropdown. update_tab_color expects a hex string like "#RRGGBB" (v3: no RGB dicts). Resize methods take zero-based inclusive/exclusive indexes. ```python async def format(self, ranges: str | list[str], format: dict) -> dict: # line 1980 @_nowait async def columns_auto_resize(self, start_column_index: int, end_column_index: int): # line 1740 async def rows_auto_resize(self, start_row_index: int, end_row_index: int): # line 2745 async def add_validation( self, range: str, condition_type: "gspread.utils.ValidationConditionType", values: Iterable, inputMessage: str | None = None, strict: bool = False, showCustomUi: bool = False, ): # line 2770 @_nowait async def update_tab_color(self, color: str): # line 3039 @_nowait async def clear_tab_color(self): # line 3063 async def hide_gridlines(self): # line 2825 async def show_gridlines(self): # line 2832 ``` -------------------------------- ### get_worksheet_by_id usage with error handling Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example of handling WorksheetNotFound when fetching by gid. Wrap the call in try/except to catch missing worksheets. ```python try: ws = await ss.get_worksheet_by_id(1234567890) except gspread.exceptions.WorksheetNotFound: print("no such gid") ``` -------------------------------- ### ClientManager construction with custom options Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/configuration.md Constructs a ClientManager with a credentials function and custom rate limiting, reauth interval, and timeout. The credentials function must be zero-argument, non-async, and thread-safe; it is called via asyncio.to_thread. gspread_timeout supports a single float or a (connect, read) tuple. ```python import gspread_asyncio from google.oauth2.service_account import Credentials def get_creds(): return Credentials.from_service_account_file( "serviceacct.json", scopes=["https://www.googleapis.com/auth/spreadsheets"] ) cm = gspread_asyncio.ClientManager( get_creds, gspread_delay=2.0, # slower than Google's default limit reauth_interval=30, # refresh every 30 minutes gspread_timeout=(5, 30), # connect timeout 5s, read timeout 30s ) ``` -------------------------------- ### Remove a permission using list_permissions and remove_permission Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Example usage: retrieves the permission list for a spreadsheet and removes the first permission using its id. ```python perms = await c.list_permissions(ss.id) await c.remove_permission(ss.id, perms[0]["id"]) ``` -------------------------------- ### Spreadsheet constructor signature Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Constructor signature for the Spreadsheet wrapper. Instances must be obtained from Client.open, Client.open_by_key, Client.open_by_url, Client.openall, Client.create, or Client.copy; do not construct directly. The cm parameter is the owning ClientManager that supplies _call, and ss is the underlying synchronous gspread spreadsheet. ```python def __init__(self, cm, ss: gspread.Spreadsheet): ``` -------------------------------- ### get_sheet1 Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Shortcut for `await self.get_worksheet(0)`. ```APIDOC ## get_sheet1 ### Description Shortcut for `await self.get_worksheet(0)`. ### Method async def get_sheet1(self) -> "Worksheet" ### Returns `Worksheet` — the first worksheet. ### Example ```python ws = await ss.get_sheet1() ``` ``` -------------------------------- ### batch_update / batch_get / batch_clear / batch_format Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/worksheet.md Methods for batch operations: updating multiple ranges, getting multiple ranges, clearing multiple ranges, and formatting multiple ranges. ```APIDOC ## batch_update / batch_get / batch_clear / batch_format ### Description These methods perform batch operations on a worksheet. `batch_update` writes values to multiple ranges, `batch_get` retrieves values from multiple ranges, `batch_clear` clears multiple ranges, and `batch_format` applies formatting to multiple ranges. ### Methods - `batch_update(data, raw=True, value_input_option=None, include_values_in_response=None, response_value_render_option=None, response_date_time_render_option=None)` - `batch_get(ranges, major_dimension=None, value_render_option=None, date_time_render_option=None) -> list` - `batch_clear(ranges)` - `batch_format(formats)` ### Parameters #### batch_update - **data** (list[dict]) - Required - List of `{"range", "values"}` objects; named ranges allowed, `None` values skipped - **raw** (bool) - Optional - Shortcut for `value_input_option="RAW"` - **value_input_option** (gspread.utils.ValueInputOption) - Optional - `RAW` or `USER_ENTERED` - **include_values_in_response** (bool) - Optional - Echo updated values - **response_value_render_option** (gspread.utils.ValueRenderOption) - Optional - Render updated values - **response_date_time_render_option** (gspread.utils.DateTimeOption) - Optional - Render date/time values #### batch_get - **ranges** (list[str]) - Required - List of A1 ranges or named ranges - **major_dimension** (str | None) - Optional - `ROWS` or `COLUMNS` - **value_render_option** (gspread.utils.ValueRenderOption) - Optional - Render values - **date_time_render_option** (gspread.utils.DateTimeOption) - Optional - Render date/time values #### batch_clear - **ranges** (list[str]) - Required - List of A1 ranges or named ranges to clear #### batch_format - **formats** (list[dict]) - Required - List of `{"range": ..., "format": {...}}` per CellFormat ### Returns - `batch_get` returns a `list`. - Others return delegated responses. ### Request Example ```python await ws.batch_update([{"range": "A1:B1", "values": [["42", "43"]]}, {"range": "my_range", "values": [["44", "45"]]}]) await ws.batch_format([{"range": "A1:C1", "format": {"textFormat": {"bold": True}}}]) ``` ``` -------------------------------- ### open_by_key method signature Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client.md Declares the async open_by_key method that takes a Google spreadsheet key. Returns a wrapped Spreadsheet served from the key cache on repeat calls. ```python async def open_by_key(self, key: str) -> "Spreadsheet": ``` -------------------------------- ### Access Spreadsheet properties Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/spreadsheet.md Example of accessing the synchronous properties id, title, locale, timezone, and url on a Spreadsheet instance. These properties read directly off the wrapped gspread.Spreadsheet and perform no I/O. ```python print(ss.id, ss.title, ss.locale, ss.timezone, ss.url) ``` -------------------------------- ### BackoffClientManager with capped backoff Source: https://github.com/dgilman/gspread_asyncio/blob/master/_autodocs/api-reference/client-manager.md Example subclass of gspread_asyncio.ClientManager that overrides handle_gspread_error to implement a capped exponential backoff. It increments a retries counter and sleeps for gspread_delay multiplied by the minimum of retries and 8. ```python class BackoffClientManager(gspread_asyncio.ClientManager): async def handle_gspread_error(self, e, method, args, kwargs): status = e.response.status_code self.retries = getattr(self, "retries", 0) + 1 await asyncio.sleep(self.gspread_delay * min(self.retries, 8)) # capped backoff ```