Cara menggunakan google-api-python-client

Keras is used by CERN, NASA, NIH, and many more scientific organizations around the world (and yes, Keras is used at the LHC). Keras has the low-level flexibility to implement arbitrary research ideas while offering optional high-level convenience features to speed up experimentation cycles.

This tutorial describes how to use the Google API Client Library for Python to call the AI Platform Prediction REST APIs in your Python applications. The code snippets and examples in the rest of this documentation use this Python client library.

You will be creating a model in your Google Cloud project in this tutorial. That is a simple task that's easily contained to a small example.

Objectives

This is a basic tutorial designed to familiarize you with this Python client library. When you're finished you should be able to:
  • Get a Python representation of the AI Platform Prediction services.
  • Use that representation to create a model in your project, which should help you understand how to call the other model and job management APIs.
Note: The code samples in this tutorial use Python 2.7. You can choose either Python 2.7 or Python 3 for use with AI Platform Prediction. See how to .

Costs

You will not be charged for the operations in this tutorial. Refer to the pricing page for more information.

Before you begin

Set up your GCP project

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  4. Enable the AI Platform Training & Prediction and Compute Engine APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  8. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  9. Enable the AI Platform Training & Prediction and Compute Engine APIs.

    Enable the APIs

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init

Set up authentication

To set up authentication, you need to create a service account key and set an environment variable for the file path to the service account key.

  1. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account

    2. In the Service account name field, enter a name.
    3. Optional: In the Service account description field, enter a description.
    4. Click Create.
    5. Click the Select a role field. Under All roles, select AI Platform > AI Platform Admin.
    6. Click Add another role.
    7. Click the Select a role field. Under All roles, select Storage > Storage Object Admin.

      Note: The roles you select allow your service account to access resources. You can view and change these roles later by using the Google Cloud console. If you are developing a production app, you might need to specify roles with fewer permissions than AI Platform Admin and Storage Object Admin. For more information, see .
    8. Click Done to create the service account.

      Do not close your browser window. You will use it in the next step.

  2. Create a service account key for authentication:

    1. In the Google Cloud console, click the email address for the service account that you created.
    2. Click Keys.
    3. Click Add key, then Create new key.
    4. Click Create. A JSON key file is downloaded to your computer.
    5. Click Close.
  3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

    Example: Linux or macOS

    Replace [PATH] with the file path of the JSON file that contains your service account key.

    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

    For example:

    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

    Example: Windows

    Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename.

    With PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

    For example:

    $env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

    With command prompt:

    set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Set up a Python development environment

Choose one of the options below to set up your environment locally on macOS or in a remote environment on Cloud Shell.

For macOS users, we recommend that you set up your environment using the MACOS tab below. Cloud Shell, shown on the CLOUD SHELL tab, is available on macOS, Linux, and Windows. Cloud Shell provides a quick way to try AI Platform Prediction, but isn't suitable for ongoing development work.

macOS

  1. Check Python installation
    Confirm that you have Python installed and, if necessary, install it.

    python -V
  2. Check

    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    5 installation
    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    5 is Python's package manager, included with current versions of Python. Check if you already have
    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    5 installed by running
    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    8. If not, .

    You can upgrade

    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    5 using the following command:

    pip install -U pip

    See the for more details.

  3. Install

    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1 is a tool to create isolated Python environments. Check if you already have
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1 installed by running
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    4. If not, install
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1:

    pip install --user --upgrade virtualenv

    To create an isolated development environment for this guide, create a new virtual environment in

    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1. For example, the following command activates an environment named
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    7:

    gcloud init
    0
  4. For the purposes of this tutorial, run the rest of the commands within your virtual environment.

    See more information about using
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1. To exit
    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    1, run
    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    0.

Cloud Shell

  1. Open the Google Cloud console.

    Google Cloud console

  2. Click the Activate Google Cloud Shell button at the top of the console window.

    Cara menggunakan google-api-python-client

    A Cloud Shell session opens inside a new frame at the bottom of the console and displays a command-line prompt. It can take a few seconds for the shell session to be initialized.

    Cara menggunakan google-api-python-client

    Your Cloud Shell session is ready to use.

  3. Configure the

    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    1 command-line tool to use your selected project.

    gcloud init
    1

    where

    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    2 is your project ID. (Omit the enclosing brackets.)

Install the Google API Client Library for Python

Install the Google API Client Library for Python.

This is a basic tutorial designed to familiarize you with this Python client library. When you're finished you should be able to:

  • Get a Python representation of the AI Platform Prediction services.
  • Use that representation to create a model in your project, which should help you understand how to call the other model and job management APIs.
Note: The code samples in this tutorial use Python 2.7. You can choose either Python 2.7 or Python 3 for use with AI Platform Prediction. See how to .You will not be charged for the operations in this tutorial. Refer to the pricing page for more information.

Importing the required modules

When you want to use the Google API Client Library for Python to call the AI Platform Prediction REST APIs in your code, you must import its package and the OAuth2 package. For this tutorial (and for most standard uses of AI Platform Prediction) you only need to import specific modules:

  • $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    3 from OAuth2
  • $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    4 from Google API Client Library for Python.
  • $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    5 from Google API Client Library for Python

Refer to the documentation for those packages to learn about the other available modules.

Create a new Python file using your favorite editor, and add these lines:

gcloud init
2

Building a Python representation of the API

Get your Python representation of the REST API. The method you call is

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
6 because the API client library uses service discovery to dynamically set up connections to the services as they exist when you make the call. Call your object that encapsulates the services
$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
7:

gcloud init
3

Configuring your parameters and request body

To make a call to a service, you must create the parameters and request body that will be passed to the REST API. You pass parameters as regular Python parameters to the method that represents the call. The body is a JSON resource just as you would use if calling the API with an HTTP request directly.

Take a look at the REST API for creating a model in a new browser tab, projects.models.create:

  • Notice the path parameter

    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    8, which is the part of the URI of the request that identifies the project. If you were making the HTTP POST request directly, you would use the following URI:

    gcloud init
    4

    When using the API client library, the variable part of the URI is represented as a string-typed parameter to the API call. You'll set it to

    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    9. Store your project in a variable to make API calls cleaner:

    gcloud init
    5
  • The body of the request is a JSON resource representing the model information. You can see in the that it has two values for input: name and (optionally) description. You can pass a Python dictionary in the place of JSON and the API client library will perform the necessary conversion.

    Create your Python dictionary:

    gcloud init
    6

Creating your request

Making calls to APIs with the Python client library has two steps: first you create a request, then you make the call using that request.

Create the request

Use the built client objects that you created earlier (if you followed the code snippet exactly, it's called

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
7) as the root of the API hierarchy and specify the API you want to use. Each collection in the API path behaves like a function that returns a list of the collections and methods within it. For example, the root of all the AI Platform Prediction APIs is
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
1, so your call begins with
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
2.

Use this code to form your request:

gcloud init
7

Send the request

The request that you constructed in the last step exposes an

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
3 method that you call to send the request to the service:

gcloud init
8

It's common for developers to combine this step with the last one:

gcloud init
9

Handle simple errors

A lot of things can go wrong when you make API calls over the Internet. It's a good idea to handle common errors. The simplest way to deal with errors is to put your request in a

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
4 block and catch likely errors. Most of the errors you're likely to get from the service are HTTP errors, which are encapsulated in the
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
5 class. To catch these errors, you'll use the
$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
5 module from the
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
7 package.

Wrap your

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
8 call in a
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
4 block. Also put a
set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
0 statement in the block, so that you will try to print the response only if the call succeeds:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
0

Add a catch block to handle HTTP errors. You can use

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
1 to get the reason text fields from the response:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
1

Of course, a simple print statement might not be the right approach for your application.

Putting it all together

Here is the complete example:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
2

Generalizing to other methods

You can use the procedure you learned here to make any of the other REST API calls. Some of the APIs require much more complicated JSON resources than creating a model does, but the principles are the same:

  1. Import

    set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
    2 and
    set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
    3.

  2. Use the discovery module to build a Python representation of the API.

  3. Use the API representation as a series of nested objects to get to the API you want and create a request. For example,

    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
    3
  4. Call

    $env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"
    8 to send the request, handling exceptions in an appropriate way for your application.

  5. When there is a response body, you can treat it like a Python dictionary to get at the JSON objects specified in the API reference. Note that many of the objects in responses have fields that are present only in some circumstances. You should always check to avoid key errors: