Skip to content

Latest commit

 

History

History
195 lines (148 loc) · 7.92 KB

getting-started.md

File metadata and controls

195 lines (148 loc) · 7.92 KB

Getting started with client libraries

The Google Cloud Libraries for Python are a mixture of handwritten and autogenerated libraries connecting to Google Cloud services. The handwritten libraries (such as google-cloud-firestore and google-cloud-spanner) are mostly higher level abstractions over the underlying API. See the documentation for those individual libraries for details; the documentation here is primarily aimed at the autogenerated libraries.

If you haven't already found the library for the API you're interested in, please consult the list of Python libraries which shows both the package name and the link to the library-specific documentation. In particular, each library has:

  • A "getting started" page which lists the client types within that library
  • Version history for the library
  • API reference documentation

This page demonstrates using the google-cloud-translate API as a simple example; the steps required for other APIs are very similar.

Prerequisites

All Google Cloud APIs require a Google Cloud project. If you haven't set one up already, please create one. You'll also need to enable your chosen API if it hasn't already been used within that Google Cloud project.

There are no specific tools required to develop using the Google Cloud Libraries for Python. All development environments should work, but you should check that you're targeting a supported version of Python.

We recommend installing the gcloud CLI.

Install the library

All Google Cloud Libraries for Python are available from PyPI and can be installed using pip. If you wish to install a pre-release version, you can specify the version explicitly with the installation command.

The libraries can be installed in any regular environment, including virtual environments (recommended), containerized applications, and web frameworks like Django or Flask.

For the translation example, we'll create a new directory, set up a virtual environment, and install the package.

Note that for simplicity, the sample code below uses synchronous calls. Most libraries also provide asynchronous clients (usually with suffix AsyncClient, rather than Client) for use in naturally asynchronous environments using asyncio.

mkdir TranslationExample
cd TranslationExample
python3 -m venv venv
source venv/bin/activate
pip install google-cloud-translate

Dependencies If you install the library, you may notice transitive dependencies being installed. This is entirely expected, but you may not recognize some of those dependencies. The list below is not comprehensive, but highlights some of the packages you'll see being installed.

  • protobuf: the library supporting the Protocol Buffers serialization format
  • google-api-core: support libraries specifically tailored for the Google Cloud client libraries
  • google-auth: authentication support for Google Cloud credentials
  • grpcio: support for the gRPC RPC protocol
  • google-cloud-core: common helpers and support for long-running operations

Create a client

The first step in making any API calls is to create a client. Some libraries have multiple clients for operations involving different resources; others have a single client. In the Translation API we're using, we use TranslationServiceClient which can be used to create a synchronous client.

Clients can be configured in a number of ways, but in many cases the defaults are fine. The most common reason to use an explicit configuration is to specify credentials for authentication. For this example, we'll just use Application Default Credentials (ADC). To set up ADC in your local environment, follow the instructions in Local development environment. When you create a client, it automatically detects and uses these credentials.

To create a client with default settings:

from google.cloud import translate_v3 as translate

client = translate.TranslationServiceClient()

Make requests

The Google Cloud Libraries use Protocol Buffers to represent requests and responses, with some additional types to make the APIs more convenient to work with.

Most APIs are expressed in terms of a single request returning a single response, although there are also streaming APIs requiring multiple requests and/or multiple responses. For our Translation API example, we'll create a simple request for the translate_text API.

from google.cloud import translate_v3 as translate

client = translate.TranslationServiceClient()

project_id = "your-project-id-here"
location_id = "global"
parent = f"projects/{project_id}/locations/{location_id}"
request = translate.TranslateTextRequest(
    contents=["It is raining.", "It is sunny."],
    target_language_code="fr-FR",
    parent=parent
)

response = client.translate_text(request=request)

This example demonstrates a few features:

  • Protocol Buffer messages are instantiated with keyword arguments representing the fields
  • Repeated fields (like contents) are represented as Python lists
  • The parent field is a string representation of a resource name. The library provides helper methods on the client to construct these paths, ensuring you don't need to concern yourself with the underlying resource name format.
    # produces the string `projects/your-project-id-here/locations/global`
    parent = client.location_path(project_id, location_id)

The Google Cloud Libraries always expose methods accepting an API request object directly, but they also support passing keyword arguments directly to the method for convenience:

response = client.translate_text(
    contents=["It is raining.", "It is sunny."],
    target_language_code="fr-FR",
    parent=parent,
)

The response is also a Protocol Buffers message. You can inspect the structure of the response by printing it, or by accessing its attributes directly. In this case we'll look at the translations attribute:

print(f"Translations returned: {len(response.translations)}")
print()
for translation in response.translations:
    print(f"Detected language: {translation.detected_language_code}")
    print(f"Translated text: {translation.translated_text}")

This produces output of:

Translations returned: 2

Detected language: en
Translated text: Il pleut.

Detected language: en
Translated text: Il fait beau.

The complete code is:

from google.cloud import translate_v3 as translate

client = translate.TranslationServiceClient()

project_id = "your-project-id-here"
location_id = "global"
parent = f"projects/{project_id}/locations/{location_id}"

request = translate.TranslateTextRequest(
    contents=["It is raining.", "It is sunny."],
    target_language_code="fr-FR",
    parent=parent,
)

response = client.translate_text(request=request)

print(f"Translations returned: {len(response.translations)}")
print()
for translation in response.translations:
    print(f"Detected language: {translation.detected_language_code}")
    print(f"Translated text: {translation.translated_text}")

This is just a simple example, which hasn't touched on features like pagination or specifying call configurations like timeouts and retries.