Google API Client Library for Python
repository·main·Indexed 27 days ago
https://github.com/googleapis/google-api-python-clientA discovery-based Python client library for interacting with Google's APIs. It provides a comprehensive, single-package solution to access a wide range of Google services, simplifying API calls and authentication (API Keys, OAuth 2.0). The library supports Python 3.7 and newer, offering core reference documentation for the googleapiclient module and specific guides for tasks such as media uploads, pagination, and thread safety.
What's inside google-api-python-client
- The Google API Client Library for Python provides a simple and flexible way for Python client-application developers to access many Google APIs. It simplifies calling Google APIs and handling authentication with minimal code, using standard Python installation tooling.
Access documentation for Google API dynamic services
mainThe
docs/dyn/directory contains dynamically generated documentation for various Google API services and their specific versions. You can find detailed API references, method signatures, and resource schemas for each service by navigating to the corresponding versioned URL.Commonly used services available in this segment include:
- My Business APIs:
mybusinessaccountmanagement,mybusinessbusinessinformation,mybusinesslodging,mybusinessnotifications,mybusinessplaceactions,mybusinessqanda,mybusinessverifications. - Networking & Security:
netapp,networkconnectivity,networkmanagement,networksecurity,networkservices,osconfig,oslogin,privateca,publicca,pubsub,pubsublite,securitycenter,securityposture,servicenetworking. - Identity & Access:
oauth2,orgpolicy,policyanalyzer,policysimulator,policytroubleshooter. - Developer & Cloud Tools:
notebooks,pagespeedonline,parallelstore,people,places,playintegrity,run,secretmanager,serviceusage. - Advertising & Commerce:
adexchangebuyer2,adexperiencereport,adsense,adsenseplatform,realtimebidding,searchads360.
- My Business APIs:
Test samples and snippets
mainCode samples and snippets are located in the
samples/directory. Each folder containing example code requires its ownnoxfile.pyscript. To test a specific sample folder:- Navigate to the sample directory (e.g.,
samples/snippets). - Run the appropriate
noxsession (e.g.,py-3.8).
Note: Sample tests run against a real Google Cloud Project and require authentication configuration similar to System Tests.
# Run all tests in a folder $ cd samples/snippets $ nox -s py-3.8 # Run a single sample test $ cd samples/snippets $ nox -s py-3.8 -- -k <name of test>- Navigate to the sample directory (e.g.,
Install the Google API Python client
mainIt is recommended to install this library within a
virtualenvto avoid dependency conflicts and permission issues. Follow the steps for your operating system below.### Mac/Linux ```bash pip3 install virtualenv virtualenv <your-env> source <your-env>/bin/activate <your-env>/bin/pip install google-api-python-clientWindows
pip install virtualenv virtualenv <your-env> <your-env>\Scripts\activate <your-env>\Scripts\pip.exe install google-api-python-clientRun tests using nox
mainThe project uses
noxto instrument and run tests. You can run unit tests, system tests, or coverage checks using specific session names.Unit Tests
- Run all unit tests:
nox -s unit - Run a single unit test:
nox -s unit-<python_version> -- -k <test_name>(e.g.,nox -s unit-3.14 -- -k my_test_function)
System Tests Note: System tests are only configured to run under Python 3.8. They require local authentication (e.g., via
gcloud) or a service account.- Run all system tests:
nox -s system - Run a single system test:
nox -s system-3.8 -- -k <test_name>
Coverage and Documentation
- Check test statement coverage:
nox -s cover(100% coverage is required) - Build HTML documentation:
nox -s docs
- Run all unit tests:
Set up the Compute Engine environment
mainBefore using the Compute Engine samples, ensure you have a Google Cloud project with billing enabled. You must install the Google Cloud SDK, authenticate using application default credentials, and install thegoogle-api-python-clientlibrary. Additionally, enable the Cloud Storage API and create a Cloud Storage bucket to use with the samples.Call Google APIs with authorized credentials
mainAfter obtaining
credentialsfrom the OAuth flow, use thebuildfunction to create a service object, then execute API requests through that object.from googleapiclient.discovery import build # 1. Build the service object drive_service = build('drive', 'v3', credentials=credentials) # 2. Make requests files = drive_service.files().list().execute()Authenticate with Authorized API access (OAuth 2.0)
mainUse OAuth 2.0 for calls accessing private user data. This requires the user to grant your application access via specific Scopes.
Key concepts:
- Scopes: Declare the set of operations permitted (e.g., read-only vs. read-write).
- Tokens: The authorization server provides access tokens (used to authorize calls) and refresh tokens (used to acquire new access tokens when they expire).
- Client ID and Client Secret: Unique identifiers for your application created in the Google Cloud API Access pane. Common types include Web application, Installed application, and Service Account client IDs.
Warning: Keep refresh tokens, access tokens, and client secrets private.
Call Google APIs with a Credentials object
mainOnce you have a
credentialsobject, follow these steps to call an API:- Build the service object: Use
googleapiclient.discovery.build()with the API name, version, and yourcredentials. - Execute requests: Use the methods provided by the service object and call
.execute()on the request object.
import googleapiclient.discovery # 1. Build the service sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta3', credentials=credentials) # 2. Make the request response = sqladmin.instances().list(project='example-123').execute()- Build the service object: Use
Install required libraries for OAuth 2.0
mainTo use service accounts and the Google API Client Library for Python, install the following dependencies:
pip install google-auth google-auth-httplib2 google-api-python-clientPerform partial updates with patch()
mainIf the specific Google API you are using supports it, use thepatch()method instead of a full update. This allows you to send only the arguments you wish to modify, avoiding the overhead of sending unnecessary data for the entire resource.Handle API responses and errors
mainThe
execute()method returns a Python object built from the JSON response sent by the API server. You can access data using standard dictionary/list indexing.To handle errors, catch
HttpErrorto access the status code and error details.