### Install Aiogoogle Source: https://aiogoogle.readthedocs.io/en/latest/index.html Use pip to install the aiogoogle package in your environment. ```bash $ pip install aiogoogle ``` -------------------------------- ### Install Local Development Version Source: https://aiogoogle.readthedocs.io/en/latest/index.html Steps to remove the existing package and install the local repository in editable mode. ```bash $ pip uninstall aiogoogle $ cd {cloned_aiogoogle_repo_with_your_local_changes} $ pip install -e . ``` -------------------------------- ### Install Aiogoogle with Curio Support Source: https://aiogoogle.readthedocs.io/en/latest/index.html Installs Aiogoogle with extra dependencies for Curio framework support. ```bash pip install aiogoogle[curio_asks] ``` -------------------------------- ### Install Aiogoogle with Trio Support Source: https://aiogoogle.readthedocs.io/en/latest/index.html Installs Aiogoogle with extra dependencies for Trio framework support. ```bash pip install aiogoogle[trio_asks] ``` -------------------------------- ### Browse API resources and methods Source: https://aiogoogle.readthedocs.io/en/latest/index.html Examples of inspecting API discovery documents, resources, and available methods programmatically. ```python >>> url_shortener['resources'] { 'url': { 'methods': 'get': ... 'insert': ... 'list': ... } ``` ```python >>> url_resource = url_shortener.url >>> url_resource.methods_available ``` ```python ['get', 'insert', 'list'] ``` ```python >>> url_resource.resources_available [] ``` ```python >>> list_url = url_resource.list ``` ```python >>> list_url['description'] "Retrieves a list of URLs shortened by a user." ``` ```python >>> list_url.optional_parameters ['projection', 'start_token', 'alt', 'fields', 'key', 'oauth_token', 'prettyPrint', 'quotaUser'] ``` ```python >>> list_url.required_parameters [] ``` ```python >>> list_url.parameters['start_token'] { "type": "string", "description": "Token for requesting successive pages of results.", "location": "query" } ``` ```python >>> request = list_url(start_token='a_string', key='a_secret_key') # Equivalent to: >>> request = url_shortener.url.list(start_token='a_start_token', key='a_secret_key') ``` ```python >>> request.url 'https://www.googleapis.com/url/history?start_token=a_start_token&key=a_secret_key' ``` -------------------------------- ### Retrieve User Information via OpenID Connect Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Example of the expected dictionary structure returned by the get_user_info method. ```python >>> await get_user_info(user_creds) { "kind": "plus#personOpenIdConnect", "gender": string, "sub": string, "name": string, "given_name": string, "family_name": string, "profile": string, "picture": string, "email": string, "email_verified": "true", "locale": string, "hd": string } ``` -------------------------------- ### Example OpenID Connect User Info Payload Source: https://aiogoogle.readthedocs.io/en/latest/index.html A sample JSON structure representing the claims returned in the full_user_info dictionary. ```json { "iss": "https://accounts.google.com", "azp": "1234987819200.apps.googleusercontent.com", "aud": "1234987819200.apps.googleusercontent.com", "sub": "10769150350006150715113082367", "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q", "hd": "example.com", "email": "jsmith@example.com", "email_verified": "true", "iat": 1353601026, "exp": 1353604926, "nonce": "0394852-3190485-2490358" } ``` -------------------------------- ### GET /list_api Source: https://aiogoogle.readthedocs.io/en/latest/index.html Retrieves a list of all APIs supported by the Google APIs Discovery Service. ```APIDOC ## GET /list_api ### Description Returns the list of all APIs supported by the Google APIs Discovery Service. The data for each entry is a subset of the Discovery Document for that API. ### Method GET ### Parameters #### Query Parameters - **name** (str) - Optional - Only include APIs with the given name. - **preferred** (bool) - Optional - Return only the preferred version of an API. Defaults to false. - **fields** (str) - Optional - Selector specifying which fields to include in a partial response. ### Response #### Success Response (200) - **kind** (str) - The type of the response object. - **discoveryVersion** (str) - The version of the discovery service. - **items** (list) - A list of supported APIs. #### Response Example { "kind": "discovery#directoryList", "discoveryVersion": "v1", "items": [ { "id": "youtube:v3", "name": "youtube", "version": "v3", "title": "YouTube Data API", "preferred": true } ] } ``` -------------------------------- ### Get User Information (v2 ME) Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Fetches detailed information about the user associated with the provided access token. This endpoint is intended for the user who is also the client. ```python req = self.oauth2_api.userinfo.v2.me.get() authorized_req = self.authorize(req, user_creds) return await self._send_request(authorized_req) ``` -------------------------------- ### Get Token Information Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Retrieves information about an access token. Requires a UserCreds instance containing the access token. ```python req = self.oauth2_api.tokeninfo(access_token=user_creds.get("access_token")) return await self._send_request(req) ``` -------------------------------- ### Translate text using API key authentication Source: https://aiogoogle.readthedocs.io/en/latest/index.html Example of using the Google Translate API with an API key to perform a translation request. ```python #!/usr/bin/python3.7 import asyncio, pprint from aiogoogle import Aiogoogle api_key = 'abc123' async def translate_to_latin(words): async with Aiogoogle(api_key=api_key) as aiogoogle: language = await aiogoogle.discover('translate', 'v2') words = dict(q=[words], target='la') result = await aiogoogle.as_api_key( language.translations.translate(json=words) ) pprint.pprint(result) if __name__ == '__main__': asyncio.run(translate_to_latin('Aiogoogle is awesome')) ``` ```json { "data": { "translations": [ { "translatedText": "Aiogoogle est terribilis!", # Google probably meant "awesomelis", but whatever.. "detectedSourceLanguage": "en" } ] } } ``` -------------------------------- ### Initialize ServiceAccountCreds Source: https://aiogoogle.readthedocs.io/en/latest/index.html Demonstrates how to instantiate ServiceAccountCreds using a JSON key file, either by passing the object directly or using a dictionary. ```python service_account_creds = ServiceAccountCreds( scopes=["https://www.googleapis.com/auth/cloud-platform"], **json.load(open('service-account-key.json')) ) # or service_account_creds = { "scopes": ["..."], **json.load(open('service-account-key.json')) } ``` -------------------------------- ### Initialize MediaDownload Object Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/models.html Handles media downloads, configuring the file path, chunk size for writing, and an optional pipe_to object for streaming. ```python class MediaDownload: def __init__(self, file_path=None, chunk_size=None, pipe_to=None): self.file_path = file_path self.pipe_to = pipe_to self.chunk_size = chunk_size or DEFAULT_DOWNLOAD_CHUNK_SIZE ``` -------------------------------- ### GET _get_user_info Source: https://aiogoogle.readthedocs.io/en/latest/index.html Retrieves user information after performing an OpenID connect flow. ```APIDOC ## GET _get_user_info ### Description Get user information after performing an OpenID connect flow. Use this method instead of people.get when you need the OpenID Connect format. ### Parameters #### Request Body - **user_creds** (aiogoogle.auth.creds.UserCreds) - Required - User credentials ### Response #### Success Response (200) - **kind** (string) - plus#personOpenIdConnect - **gender** (string) - User gender - **sub** (string) - Subject identifier - **name** (string) - Full name - **email** (string) - User email - **email_verified** (string) - Verification status ``` -------------------------------- ### Get User Info Source: https://aiogoogle.readthedocs.io/en/latest/index.html Retrieves information about the user associated with the provided access token. ```APIDOC ## GET /get_me_info ### Description Gets information about the user based on their access token. ### Method GET ### Endpoint /get_me_info ### Parameters #### Query Parameters - **user_creds** (UserCreds) - Required - UserCreds instance with a valid access token. ### Response #### Success Response (200) - **user_info** (dict) - A dictionary containing information about the user. #### Response Example ```json { "user_info": { "id": "user_id", "email": "example@gmail.com", "verified_email": true, "name": "Example User" } } ``` ### Raises - **aiogoogle.excs.HTTPError** - If the API request fails. ``` -------------------------------- ### Get Token Info Source: https://aiogoogle.readthedocs.io/en/latest/index.html Retrieves information about an access token, such as its validity, scopes, and expiration. ```APIDOC ## GET /oauth2/token_info ### Description Retrieves information about a given access token. ### Method GET ### Endpoint /oauth2/token_info ### Parameters #### Query Parameters - **access_token** (str) - Required - The access token to get information for. ### Response #### Success Response (200) - **info** (dict) - A dictionary containing information about the token (e.g., expiration, scopes, user ID). #### Response Example ```json { "info": { "expires_at": 1698397200, "issued_to": "client_id", "audience": "client_id", "user_id": "user_id", "scope": "first.scope second.scope", "expires_in": 3600 } } ``` ``` -------------------------------- ### Use Aiogoogle with Curio Source: https://aiogoogle.readthedocs.io/en/latest/index.html Demonstrates initializing Aiogoogle with a `CurioAsksSession` for use with the Curio async framework. ```python import curio from aiogoogle import Aiogoogle from aiogoogle.sessions.curio_asks_session import CurioAsksSession async def main(): async with Aiogoogle(session_factory=CurioAsksSession) as aiogoogle: youtube = await aiogoogle.discover('youtube', 'v3') curio.run(main) ``` -------------------------------- ### GET GCE Metadata Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Internal method to verify GCE environment by pinging the metadata server. ```APIDOC ## GET [GCE_METADATA_IP_ROOT] ### Description Pings the Google Compute Engine metadata server to verify if the application is running in a GCE environment. ### Method GET ### Endpoint [GCE_METADATA_IP_ROOT] ### Response #### Success Response (200) - **Metadata-Flavor** (header) - Must match GCE_METADATA_FLAVOR_VALUE to confirm GCE environment. ``` -------------------------------- ### Authenticate via GOOGLE_APPLICATION_CREDENTIALS Source: https://aiogoogle.readthedocs.io/en/latest/index.html Set the environment variable to point to the key file, then use detect_default_creds_source to load credentials. ```bash export GOOGLE_APPLICATION_CREDENTIALS="location_of_key_file.json" ``` ```python import asyncio import print from aiogoogle import Aiogoogle from aiogoogle.auth.creds import ServiceAccountCreds creds = ServiceAccountCreds( scopes=[ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/devstorage.read_write", "https://www.googleapis.com/auth/devstorage.full_control", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/cloud-platform", ], ) async def list_storage_buckets(project_id=creds["project_id"]): aiogoogle = Aiogoogle(service_account_creds=creds) # Notice this line. Here, Aiogoogle loads the service account key. await aiogoogle.service_account_manager.detect_default_creds_source() async with aiogoogle: storage = await aiogoogle.discover("storage", "v1") res = await aiogoogle.as_service_account( storage.buckets.list(project=creds["project_id"]) ) print(res) if __name__ == "__main__": asyncio.run(list_storage_buckets()) ``` -------------------------------- ### ServiceAccountManager Initialization Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Details on how to initialize the ServiceAccountManager, including session factory and credentials. ```APIDOC ## Class: ServiceAccountManager ### Description Manages service account credentials for authenticating with Google Cloud services. ### Arguments - **session_factory** (aiogoogle.sessions.AbstractSession) - A session implementation to use for making HTTP requests. Defaults to `AiohttpSession`. - **creds** (aiogoogle.auth.creds.ServiceAccountCreds) - Service account credentials. Can be provided directly or loaded from various sources. ### Initialization Example ```python from aiogoogle.auth.creds import ServiceAccountCreds from aiogoogle.sessions import AiohttpSession # Example using a dictionary of credentials sa_creds = ServiceAccountCreds({ "type": "service_account", "project_id": "your-project-id", "private_key_id": "your-private-key-id", "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "client_email": "your-service-account-email@your-project-id.iam.gserviceaccount.com", "client_id": "your-client-id", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/your-service-account-email%40your-project-id.iam.gserviceaccount.com" }) manager = ServiceAccountManager(session_factory=AiohttpSession, creds=sa_creds) ``` ``` -------------------------------- ### GET Authorization URL Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Generates an authorization URI to redirect users for OAuth2/OpenID Connect authentication. ```APIDOC ## GET /authorization_url ### Description Generates the authorization URI required to start the OAuth2 or OpenID Connect flow. This URI directs the user to the provider's login page. ### Method GET ### Parameters #### Query Parameters - **client_creds** (ClientCreds) - Required - Contains client_id, scopes, and redirect_uri. - **nonce** (str) - Required - Random value to prevent replay attacks. - **state** (str) - Optional - CSRF protection token. - **access_type** (str) - Optional - 'offline' for refresh tokens. - **include_granted_scopes** (bool) - Optional - Whether to include previously granted scopes. - **login_hint** (str) - Optional - Email address to pre-fill the login screen. - **prompt** (str) - Optional - 'select_account' to force account selection. ### Response #### Success Response (200) - **uri** (str) - The generated authorization URI. ``` -------------------------------- ### Initialize ServiceAccountCreds from JSON file Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/creds.html Initializes a ServiceAccountCreds object by loading credentials from a JSON key file. Ensure the file contains necessary fields like client_email, private_key, etc. ```python service_account_creds = ServiceAccountCreds( scopes=["https://www.googleapis.com/auth/cloud-platform"], **json.load(open('service-account-key.json')) ) # or service_account_creds = { "scopes": ["..."], **json.load(open('service-account-key.json')) } ``` -------------------------------- ### GET /authorization_url Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Generates an OAuth2 authorization URI for the first step of the authorization code flow. ```APIDOC ## GET /authorization_url ### Description First step of OAuth2 authorization code flow. Creates an OAuth2 authorization URI. ### Method GET ### Parameters #### Query Parameters - **client_creds** (aiogoogle.auth.creds.ClientCreds) - Required - Contains client_id, scopes, and redirect_uri - **nonce** (str) - Optional - Replay protection value - **state** (str) - Optional - CSRF token - **prompt** (str) - Optional - Prompt behavior - **display** (str) - Optional - UI display mode - **login_hint** (str) - Optional - Login hint - **access_type** (str) - Optional - Access type - **include_granted_scopes** (bool) - Optional - Include previously granted scopes - **openid_realm** (str) - Optional - OpenID realm - **hd** (str) - Optional - Hosted domain - **response_type** (str) - Optional - Response type (default: code) - **scopes** (list) - Optional - List of OAuth2 scopes ``` -------------------------------- ### GET /userinfo Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Retrieves user information after performing an OpenID connect flow using user credentials. ```APIDOC ## GET /userinfo ### Description Get user information after performing an OpenID connect flow. Use this method instead of people.get when you need the OpenID Connect format. ### Method GET ### Parameters #### Request Body - **user_creds** (aiogoogle.auth.creds.UserCreds) - Required - User credentials object ### Response #### Success Response (200) - **kind** (string) - The type of object - **gender** (string) - User gender - **sub** (string) - Subject identifier - **name** (string) - Full name - **given_name** (string) - Given name - **family_name** (string) - Family name - **profile** (string) - Profile URL - **picture** (string) - Picture URL - **email** (string) - Email address - **email_verified** (string) - Verification status - **locale** (string) - Locale - **hd** (string) - Hosted domain ### Response Example { "kind": "plus#personOpenIdConnect", "gender": "string", "sub": "string", "name": "string", "given_name": "string", "family_name": "string", "profile": "string", "picture": "string", "email": "string", "email_verified": "true", "locale": "string", "hd": "string" } ``` -------------------------------- ### Create a URL-shortener Google API instance Source: https://aiogoogle.readthedocs.io/en/latest/index.html Initializes an Aiogoogle instance and discovers the API specification for the specified service. ```python import asyncio from aiogoogle import Aiogoogle async def create_api(name, version): async with Aiogoogle( user_creds={'access_token': '...', 'refresh_token': '...'} ) as aiogoogle: return await aiogoogle.discover(name, version) url_shortener = asyncio.run( create_api('urlshortener', 'v1') ) ``` -------------------------------- ### Initialize MediaUpload Object Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/models.html Handles media uploads, accepting file paths or bytes. Configures upload path, MIME ranges, max size, multipart, chunk size, resumable uploads, validation, and piping. ```python class MediaUpload: def __init__( self, file_path_or_bytes, upload_path=None, mime_range=None, max_size=None, multipart=False, chunk_size=None, resumable=None, validate=True, pipe_from=None ): if isinstance(file_path_or_bytes, bytes): self.file_body = file_path_or_bytes self.file_path = None else: self.file_body = None self.file_path = file_path_or_bytes self.upload_path = upload_path self.mime_range = mime_range self.max_size = max_size self.multipart = multipart self.chunk_size = chunk_size or DEFAULT_UPLOAD_CHUNK_SIZE self.resumable = resumable self.validate = validate self.pipe_from = pipe_from ``` -------------------------------- ### Shorten a URL using an API key Source: https://aiogoogle.readthedocs.io/en/latest/index.html Demonstrates how to discover the URL Shortener API and send a request using an API key within an asynchronous context. ```python import asyncio from aiogoogle import Aiogoogle from pprint import pprint api_key = 'you_api_key' async def shorten_urls(long_url): async with Aiogoogle(api_key=api_key) as aiogoogle: url_shortener = await aiogoogle.discover('urlshortener', 'v1') short_url = await aiogoogle.as_api_key( # the request is being sent here url_shortener.url.insert( json=dict( longUrl=long_url ) ) ) return short_url short_url = asyncio.run(shorten_urls('https://www.google.com')) pprint(short_url) ``` ```json { "kind": "urlshortener#url", "id": "https://goo.gl/Dk2j", "longUrl": "https://www.google.com/" } ``` -------------------------------- ### Aiogoogle.discover() Source: https://aiogoogle.readthedocs.io/en/latest/index.html Discovers and loads Google API definitions. ```APIDOC ## Aiogoogle.discover() ### Description Discovers the available APIs and their methods, returning a GoogleAPI object. ### Response #### Success Response (200) - **GoogleAPI** (Object) - The object containing discovered resources and methods. ``` -------------------------------- ### Curio Asks Session Implementation Source: https://aiogoogle.readthedocs.io/en/latest/index.html An asynchronous session implementation using Curio and the 'asks' library, inheriting from Session and AbstractSession. Designed for use with Curio's concurrency model. ```python _class _aiogoogle.sessions.curio_asks_session.CurioAsksSession(_* args_, _** kwargs_) ``` -------------------------------- ### Get User Information Source: https://aiogoogle.readthedocs.io/en/latest/index.html Retrieves information about the user associated with the provided access token. The user must also be the client. This endpoint's exact purpose and differentiation from `get_user_info` may require further confirmation. ```python user_info = await get_me_info(user_creds) ``` -------------------------------- ### Async context management for Aiogoogle Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/client.html These methods implement asynchronous context management for Aiogoogle. `__aenter__` ensures a session is available and enters it, while `__aexit__` exits the session and cleans up by setting the session context to `None`. ```python async def __aenter__(self): session = self._get_session() if session is None: session = self._set_session() await session.__aenter__() return self raise RuntimeError("Nesting context managers using the same Aiogoogle object is not allowed.") ``` ```python async def __aexit__(self, *args): session = self._get_session() await session.__aexit__(*args) # Had to add this because there's no use of keeping a closed session # Closed sessions cannot be reopened, so it's better to just get rid of the object self.session_context.set(None) ``` -------------------------------- ### ServiceAccountManager Initialization Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Initializes the ServiceAccountManager with an optional session factory and credentials. The session factory defaults to AiohttpSession. Credentials can be provided directly or will be managed internally. ```python def __init__( self, session_factory=AiohttpSession, creds=None ): self.session_factory = session_factory self.creds = creds or {} self._access_token = None self._expires_at = None self.__creds_source = 'key_file' ``` -------------------------------- ### Get Discovery Document Item Source: https://aiogoogle.readthedocs.io/en/latest/index.html Retrieves specific items from a GoogleAPI object's discovery document using dictionary-like key access. This is useful for inspecting API metadata like name, ID, version, or OAuth scopes. ```python google_service = GoogleAPI(google_books_discovery_doc) google_service['name'] ``` ```python google_service['id'] ``` ```python google_service['version'] ``` ```python google_service['documentationLink'] ``` ```python google_service['oauth2']['scopes'] ``` -------------------------------- ### Handle OpenID Connect Callback Source: https://aiogoogle.readthedocs.io/en/latest/index.html Processes the authorization code to retrieve user credentials and information. Use the 'sub' claim for unique user identification. ```python @app.route('/callback/aiogoogle') async def callback(request): if request.args.get('error'): error = { 'error': request.args.get('error'), 'error_description': request.args.get('error_description') } return response.json(error) elif request.args.get('code'): # Returns an access and refresh token full_user_creds = await aiogoogle.openid_connect.build_user_creds( grant=request.args.get('code'), client_creds=CLIENT_CREDS, nonce=nonce, # Same nonce as above verify=False ) # A dict having claims of the user e.g. the sub claim and iat claim. # Check https://developers.google.com/identity/protocols/oauth2/openid-connect#an-id-tokens-payload for more info full_user_info = await aiogoogle.openid_connect.get_user_info(full_user_creds) # Here you should save both full_user_creds and full_user_info to a db if your app will be serving multiple users. return response.text( f"full_user_creds: {pprint.pformat(full_user_creds)}\n\nfull_user_info: {pprint.pformat(full_user_info)}" ) else: # Should either receive a code or an error return response.text("Something's probably wrong with your callback") ``` -------------------------------- ### Trio Asks Session Implementation Source: https://aiogoogle.readthedocs.io/en/latest/index.html An asynchronous session implementation using Trio and the 'asks' library, inheriting from Session and AbstractSession. Tailored for use within the Trio concurrency framework. ```python _class _aiogoogle.sessions.trio_asks_session.TrioAsksSession(_* args_, _** kwargs_) ``` -------------------------------- ### Aiogoogle Initialization Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/client.html The Aiogoogle class serves as the main entry point for interacting with Google APIs. It can be initialized with various authentication credentials and session factories. ```APIDOC ## Aiogoogle Class ### Description Main entry point for Aiogoogle, acting as a wrapper around Discovery Service, authentication managers, and session objects. ### Arguments - **session_factory** (aiogoogle.sessions.abc.AbstractSession) - AbstractSession Implementation. Defaults to ``aiogoogle.sessions.aiohttp_session.AiohttpSession`` - **api_key** (aiogoogle.auth.creds.ApiKey) - Google API key - **user_creds** (aiogoogle.auth.creds.UserCreds) - OAuth2 user credentials - **client_creds** (aiogoogle.auth.creds.ClientCreds) - OAuth2 client credentials - **service_account_creds** (aiogoogle.auth.creds.ServiceAccountCreds) - Service account credentials ### Initialization Example ```python from aiogoogle import Aiogoogle # Using default session factory aiogoogle = Aiogoogle() # Using a custom session factory # sess = lambda: Session(your_custome_arg, your_custom_kwarg=True) # aiogoogle = Aiogoogle(session_factory=sess) ``` ``` -------------------------------- ### Initialize TokenInfo Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/creds.html Initializes a TokenInfo object with various token-related attributes. Used to store information about an OAuth2 token. ```python def __init__( self, access_token=None, refresh_token=None, expires_in=None, expires_at=None, scopes=None, id_token=None, id_token_jwt=None, token_type=None, token_uri=None, token_info_uri=None, revoke_uri=None, ): self.access_token = access_token self.refresh_token = refresh_token self.expires_in = expires_in self.expires_at = expires_at self.scopes = scopes self.id_token = id_token self.id_token_jwt = id_token_jwt self.token_type = token_type self.token_uri = token_uri self.token_info_uri = token_info_uri self.revoke_uri = revoke_uri ``` -------------------------------- ### Access User Resource Source: https://aiogoogle.readthedocs.io/en/latest/index.html Demonstrates accessing a top-level resource ('user') from a GoogleAPI object. This is done after initializing GoogleAPI with a discovery document. ```python google_service = GoogleAPI(google_service_discovery_doc) goolge_service.user ``` -------------------------------- ### List Google APIs using Discovery Service v1 Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/client.html Fetches a list of all APIs supported by the Google Discovery Service. Useful for discovering available APIs and their versions. Can filter by API name and preferred version. ```python async def list_api(self, name, preferred=None, fields=None): """ https://developers.google.com/discovery/v1/reference/apis/list The discovery.apis.list method returns the list all APIs supported by the Google APIs Discovery Service. The data for each entry is a subset of the Discovery Document for that API, and the list provides a directory of supported APIs. If a specific API has multiple versions, each of the versions has its own entry in the list. Example: :: >>> await aiogoogle.list_api('youtube') { "kind": "discovery#directoryList", "discoveryVersion": "v1", "items": [ { "kind": "discovery#directoryItem", "id": "youtube:v3", "name": "youtube", "version": "v3", "title": "YouTube Data API", "description": "Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more.", "discoveryRestUrl": "https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest", "discoveryLink": "./apis/youtube/v3/rest", "icons": { "x16": "https://www.google.com/images/icons/product/youtube-16.png", "x32": "https://www.google.com/images/icons/product/youtube-32.png" }, "documentationLink": "https://developers.google.com/youtube/v3", "preferred": true } ] } Arguments: name (str): Only include APIs with the given name. preferred (bool): Return only the preferred version of an API. "false" by default. fields (str): Selector specifying which fields to include in a partial response. Returns: dict: Raises: aiogoogle.excs.HTTPError """ request = self.discovery_service.apis.list( ``` -------------------------------- ### Initialize ResumableUpload Object Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/models.html Used in conjunction with media upload. Configures upload path, multipart support, and chunk size. ```python class ResumableUpload: def __init__(self, multipart=None, chunk_size=None, upload_path=None): self.upload_path = upload_path self.multipart = multipart self.chunk_size = chunk_size or DEFAULT_UPLOAD_CHUNK_SIZE ``` -------------------------------- ### Define String and Representation Methods Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/models.html Methods to return the content as a string and provide a descriptive representation of the response model. ```python def __str__(self): return str(self.content) def __repr__(self): return f"Aiogoogle response model. Status: {str(self.status_code)}" ``` -------------------------------- ### Execute All Validations Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/validate.html Runs the full suite of validation checks on an instance against a given schema. ```python def validate_all(instance, schema, schema_name=None): validate_type(instance, schema, schema_name) validate_format(instance, schema, schema_name) validate_range(instance, schema, schema_name) validate_pattern(instance, schema, schema_name) validate_enum(instance, schema, schema_name) ``` -------------------------------- ### Aiogoogle Main Class Initialization Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/client.html Initializes the main Aiogoogle class, setting up session factories and authentication managers. Supports various credential types like API keys, OAuth2, and service accounts. ```python class Aiogoogle: """ Main entry point for Aiogoogle. This class acts as tiny wrapper around: 1. Discovery Service v1 API 2. Aiogoogle's OAuth2 manager 3. Aiogoogle's API key manager 4. Aiogoogle's OpenID Connect manager 5. Aiogoogle's service account manager 6. One of Aiogoogle's implementations of a session object Arguments: session_factory (aiogoogle.sessions.abc.AbstractSession): AbstractSession Implementation. Defaults to ``aiogoogle.sessions.aiohttp_session.AiohttpSession`` api_key (aiogoogle.auth.creds.ApiKey): Google API key user_creds (aiogoogle.auth.creds.UserCreds): OAuth2 user credentials client_creds (aiogoogle.auth.creds.ClientCreds): OAuth2 client credentials service_account_creds (aiogoogle.auth.creds.ServiceAccountCreds): Service account credentials Note: In case you want to instantiate a custom session with initial parameters, you can pass an anonymous factory. e.g. :: >>> sess = lambda: Session(your_custome_arg, your_custom_kwarg=True) >>> aiogoogle = Aiogoogle(session_factory=sess) """ def __init__( self, session_factory=AiohttpSession, api_key=None, user_creds=None, client_creds=None, service_account_creds=None, ): self.session_factory = session_factory # Guarantees that each context manager gets its own active_session. self.session_context: ContextVar[session_factory] = ContextVar("active_session", default=None) # Keys self.api_key = api_key self.user_creds = user_creds self.client_creds = client_creds self.service_account_creds = service_account_creds # Auth managers self.api_key_manager = ApiKeyManager(api_key=self.api_key) self.oauth2 = Oauth2Manager( self.session_factory, client_creds=self.client_creds ) self.openid_connect = OpenIdConnectManager( self.session_factory, client_creds=self.client_creds ) self.service_account_manager = ServiceAccountManager( self.session_factory, creds=self.service_account_creds ) # Discovery service self.discovery_service = GoogleAPI(DISCOVERY_SERVICE_V1_DISCOVERY_DOC) ``` -------------------------------- ### Tag and Push New Version Source: https://aiogoogle.readthedocs.io/en/latest/index.html Commands to create a new Git tag and push it to the remote repository to trigger the release workflow. ```bash $ git tag -a 1.0.1 -m "New version :tada:" master $ git push --tags ``` -------------------------------- ### Set Credentials from Environment File Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Loads service account credentials from a JSON file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable. Raises a RuntimeError if the path is invalid or a ValueError if the file content is malformed. ```python def _set_creds_from_environ(self, creds_location): if not os.path.exists(creds_location): raise RuntimeError('Credentials environment path specified in: GOOGLE_APPLICATION_CREDENTIALS is invalid.') with open(creds_location, 'r') as f: try: info = json.load(f) except ValueError as e: raise ValueError('Invalid credentials file specified in GOOGLE_APPLICATION_CREDENTIALS environment variable', e) else: self.creds.update(info) self._creds_source = 'key_file' ``` -------------------------------- ### Authenticate with User-Managed Service Account Key Source: https://aiogoogle.readthedocs.io/en/latest/index.html Load a service account JSON file and pass it to ServiceAccountCreds to authorize requests. ```python import json import asyncio from aiogoogle import Aiogoogle from aiogoogle.auth.creds import ServiceAccountCreds service_account_key = json.load(open('test_service_account.json')) creds = ServiceAccountCreds( scopes=[ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/devstorage.read_write", "https://www.googleapis.com/auth/devstorage.full_control", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/cloud-platform", ], **service_account_key ) async def list_storage_buckets(project_id=creds["project_id"]): async with Aiogoogle(service_account_creds=creds) as aiogoogle: storage = await aiogoogle.discover("storage", "v1") res = await aiogoogle.as_service_account( storage.buckets.list(project=creds["project_id"]) ) print(res) if __name__ == "__main__": asyncio.run(list_storage_buckets()) ``` -------------------------------- ### Discover Google API Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/client.html Downloads a discovery document for a specified Google API. It's recommended to explicitly provide an API version to avoid an extra HTTP request. ```python async def discover(self, api_name, api_version=None, validate=False, *, disco_doc_ver: Optional[int] = None): """ Donwloads a discovery document from Google's Discovery Service V1 and sets it a ``aiogoogle.resource.GoogleAPI`` Note: It is recommended that you explicitly specify an API version. When you leave the API version as None, Aiogoogle uses the ``list_api`` method to search for the best fit version of the given API name. This will result in sending two http requests instead of just one. Arguments: api_name (str): API name to discover. *e.g.: "youtube"* api_version (str): API version to discover *e.g.: "v3" not "3" and not 3* validate (bool): Set this to True to use this lib's built in parameter validation logic. Note that you shouldn't rely on this for critical user input validation. disco_doc_ver: Specify which Google Discovery Service version to fetch a discovery document with. Useful for fetching discovery docs for Google APIs that aren't supported by the default version of the Google Discovery Service Aiogoogle uses. Returns: aiogoogle.resource.GoogleAPI: An object that will then be used to create API requests Raises: aiogoogle.excs.HTTPError """ if api_version is None: # Search for name in self.list_api and return best match discovery_list = await self.list_api(api_name, preferred=True) if discovery_list["items"]: api_name = discovery_list["items"][0]["name"] api_version = discovery_list["items"][0]["version"] else: raise ValueError("Invalid API name") request = self.discovery_service.apis.getRest( api=api_name, version=api_version, validate=False ) # Allow clients to fetch Google API discovery docs from v2 of the Google Discovery Service if disco_doc_ver == 2: request.url = GOOGLE_DISCOVERY_SERVICE_URL_FMT_V2.format( api=api_name, api_version=api_version ) discovery_document = await self.as_anon(request) return GoogleAPI(discovery_document, validate) ``` -------------------------------- ### Download File from Google Drive Source: https://aiogoogle.readthedocs.io/en/latest/index.html Downloads a specific file by ID to a local path. Requires setting alt='media' in the request. ```python async def download_file(file_id, path): async with Aiogoogle(user_creds=user_creds) as aiogoogle: drive_v3 = await aiogoogle.discover('drive', 'v3') await aiogoogle.as_user( drive_v3.files.get(fileId=file_id, download_file=path, alt='media'), ) asyncio.run(download_file('abc123', '/home/user/Desktop/my_file.zip')) ``` -------------------------------- ### Instantiate Aiogoogle with a custom session Source: https://aiogoogle.readthedocs.io/en/latest/index.html Use a lambda to pass a custom session factory with initial parameters to the Aiogoogle constructor. ```python >>> sess = lambda: Session(your_custome_arg, your_custom_kwarg=True) >>> aiogoogle = Aiogoogle(session_factory=sess) ``` -------------------------------- ### Aiohttp Session Implementation Source: https://aiogoogle.readthedocs.io/en/latest/index.html An asynchronous session implementation using aiohttp, inheriting from ClientSession and AbstractSession. Suitable for managing network requests in an asyncio environment. ```python _class _aiogoogle.sessions.aiohttp_session.AiohttpSession(_* args_, _** kwargs_) ``` -------------------------------- ### List Calendar Events with Asyncio Source: https://aiogoogle.readthedocs.io/en/latest/index.html Lists calendar events using Aiogoogle with Asyncio and the default `AiohttpSession`. Requires user and client credentials. ```python #!/usr/bin/python3.7 import asyncio, pprint from aiogoogle import Aiogoogle from aiogoogle.sessions.aiohttp_session import AiohttpSession # Default async def list_events(): async with Aiogoogle(user_creds=user_creds, client_creds=client_creds, session_factory=AiohttpSession) as aiogoogle: calendar_v3 = await aiogoogle.discover('calendar', 'v3') events = await aiogoogle.as_user( calendar_v3.events.list(calendarId='primary'), ) pprint.pprint(events) if __name__ == '__main__': asyncio.run(list_events) ``` -------------------------------- ### Execute HTTP Requests with File Upload Support Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/sessions/aiohttp_session.html Handles request execution by checking for file uploads and updating headers accordingly before dispatching the request. ```python request.headers.update({"Content-Type": request.upload_file_content_type}) return await self.request( method=request.method, url=request.media_upload.upload_path, headers=request.headers, data=read_file, json=request.json, timeout=request.timeout, verify_ssl=request._verify_ssl, ) # Else, if no file upload else: return await self.request( method=request.method, url=request.url, headers=request.headers, data=request.data, json=request.json, timeout=request.timeout, verify_ssl=request._verify_ssl, ) ``` -------------------------------- ### Shorten multiple URLs concurrently Source: https://aiogoogle.readthedocs.io/en/latest/index.html Shows how to send multiple API requests simultaneously by passing them to the as_api_key method. ```python import asyncio from aiogoogle import Aiogoogle from pprint import pprint async def shorten_url(long_urls): async with Aiogoogle(api_key=api_key) as aiogoogle: url_shortener = await aiogoogle.discover('urlshortener', 'v1') short_urls = await aiogoogle.as_api_key( url_shortener.url.insert( json=dict( longUrl=long_url[0] ), url_shortener.url.insert( json=dict( longUrl=long_url[1] ) ) return short_urls short_urls = asyncio.run( shorten_url( ['https://www.google.com', 'https://www.google.org'] ) ) pprint(short_urls) ``` ```json [ { "kind": "urlshortener#url", "id": "https://goo.gl/Dk2j", "longUrl": "https://www.google.com/" }, { "kind": "urlshortener#url", "id": "https://goo.gl/Dk23", "longUrl": "https://www.google.org/" } ] ``` -------------------------------- ### MediaDownload Model Source: https://aiogoogle.readthedocs.io/en/latest/index.html Represents parameters for downloading media files. ```APIDOC ## MediaDownload Model ### Description Represents parameters for downloading media files. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Generate OpenID Connect Authorization URL Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Creates an authorization URI for OpenID Connect flows. Requires client credentials, a state, and a nonce for security. ```python from aiogoogle.auth.utils import create_secret from aiogoogle import ClinetCreds client_creds = ClientCreds( client_id='a_client_id', scopes=['first.scope', 'second.scope'], redirect_uri='http://localhost:8080' ) state = create_secret() nonce = create_secret() auth_uri = openid_connect.authorization_url( client_creds=client_creds, nonce=nonce, state=state, access_type='offline', include_granted_scopes=True, login_hint='example@gmail.com', prompt='select_account' ) ``` -------------------------------- ### List Calendar Events with Curio Source: https://aiogoogle.readthedocs.io/en/latest/index.html Lists calendar events using Aiogoogle with Curio and `CurioAsksSession`. Requires user and client credentials. ```python #!/usr/bin/python3.7 import curio, pprint from aiogoogle import Aiogoogle from aiogoogle.sessions.curio_asks_session import CurioAsksSession async def list_events(): async with Aiogoogle(user_creds=user_creds, client_creds=client_creds, session_factory=CurioAsksSession) as aiogoogle: calendar_v3 = await aiogoogle.discover('calendar', 'v3') events = await aiogoogle.as_user( calendar_v3.events.list(calendarId='primary'), ) pprint.pprint(events) if __name__ == '__main__': curio.run(list_events) ``` -------------------------------- ### Configure GCE Metadata Timeout Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Sets the default timeout for GCE metadata requests from environment variables with a fallback to 3 seconds. ```python try: GCE_METADATA_DEFAULT_TIMEOUT = int(os.getenv("GCE_METADATA_TIMEOUT", 3)) except ValueError: # pragma: NO COVER GCE_METADATA_DEFAULT_TIMEOUT = 3 ``` -------------------------------- ### Media Download Object Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/models.html Facilitates the downloading of media files. It allows specifying a file path for saving the download, a chunk size for writing data, and an option to pipe the content to another object. ```APIDOC ## MediaDownload Class ### Description Facilitates the downloading of media files. It allows specifying a file path for saving the download, a chunk size for writing data, and an option to pipe the content to another object. ### Class Definition ```python class MediaDownload: """ Media Download Arguments: file_path (str): Full path of the file to be downloaded chunksize (int): Size of a chunk of bytes that a session should write at a time when downloading. pipe_to (object): class object to stream file content to """ def __init__(self, file_path=None, chunk_size=None, pipe_to=None): self.file_path = file_path self.pipe_to = pipe_to self.chunk_size = chunk_size or DEFAULT_DOWNLOAD_CHUNK_SIZE ``` ``` -------------------------------- ### Handle Pagination for Drive Files Source: https://aiogoogle.readthedocs.io/en/latest/index.html Uses the full_res parameter to enable asynchronous iteration over paginated results from the Drive API. ```python async def list_files(): async with Aiogoogle(user_creds=user_creds) as aiogoogle: drive_v3 = await aiogoogle.discover('drive', 'v3') full_res = await aiogoogle.as_user( drive_v3.files.list(), full_res=True ) async for page in full_res: for file in page['files']: print(file['name']) asyncio.run(list_files()) ``` -------------------------------- ### Raise RuntimeError for missing credentials Source: https://aiogoogle.readthedocs.io/en/latest/_modules/aiogoogle/auth/managers.html Use this to enforce the presence of service account credentials before proceeding with authentication. ```python raise RuntimeError( 'No service account creds found.' 'Please provide service account credentials or call self.detect_default_creds first' ) return True ```