This page discusses how you can use the Google APIs Client Library for Python to send requests to the Google Cloud Storage JSON API, using OAuth authentication.
Specifically, the sample shown here gets metadata about a bucket you specify and lists the objects in the bucket. You can use the general steps shown here to run your own code.
This document assumes that you have the latest version of Python installed, and you are familiar with Python and the Google Cloud Storage concepts and operations presented in the Getting Started: Using the Developers Console guide.
1. Set up your environment
If you already have a Python environment, you can use it to run this example. Or, you can create an environment on a Google Compute Engine instance (see Creating and starting an instance).
Using pip
To use pip to set up your environment to run the code, do the following:
$ wget https://bootstrap.pypa.io/get-pip.py $ sudo python get-pip.py $ sudo pip install --upgrade google-api-python-client httplib2 argparse
Using virtualenv
To use virtualenv to create an isolated Python environment to run the code, do the following:
$ virtualenv env $ ./env/bin/pip install --upgrade google-api-python-client httplib2 argparse $ source ./env/bin/activate
2. Create a client secrets file
The example uses a client secrets file to authenticate with the Google Cloud Storage JSON API.
To generate a client secrets file:
- Go to the Google Developers Console.
- Select a project to which the client ID will be associated.
- In the left sidebar, select APIs & auth > Credentials.
- Click Create new Client ID.
- In the Create Client ID window, choose Installed application.
- Click Create Client ID.
The resulting client ID will look like the following example:
- Click Download JSON.
3. Create your code file
In this step, you create the Python code file, storage-sample.py
. Copy the
code from below and make the following changes:
- Set
_API_VERSION
to the latest version (v1). - Set
_BUCKET_NAME
to the name of a bucket in the same project as client ID you created.
Rename the credentials file you downloaded in Step 2 to client_secrets.json
and put it in the same directory as storage-sample.py
.
storage-sample.py
4. Run the sample
When you run the sample for the first time, you will be asked to authenticate.
To run the sample:
-
Generate an authentication URL.
-
If you are running the sample on a machine where you have access to a browser, use:
$ python storage-sample.py
-
Otherwise, use the
noauth_local_webserver
switch to generate an authentication URL.$ python storage-sample.py --noauth_local_webserver
-
-
Open the authentication URL and click Accept.
-
Copy the code and complete the authentication process.