How to Use Google API to Save Your Cat’s Photo on Cloud

Open the GCP console. Use Navigation menu and select APIs & Services > Library:

Search for Google Cloud Storage API, then enable the API

Open up a Cloud Shell session by pressing the button at top right

Run the following command to create and edit a file called skyline.json:

Inside the vim text editor, copy and paste the following code that create an object that has three key-value pairs: name, location, and storageClass

{  "name": "skyline",    
"location": "us",
"storageClass": "multi_regional"

Save and exit the json file by press ESC, then type :wq, then press ENTER.

Authentication and Authorization

Authentication tells the server who you are while authorization determines what you can do.

There are three types of authentication/authorization services that Google APIs use: API Keys, Service accounts, and OAuth. Here we will use OAuth.

Open the OAuth 2.0 playground in a new tab. Select Cloud Storage JSON API V1 with full control, then click the blue button Authorize APIs.

After sign-in with your google username, you will see following page.

Click on Exchange authorization code for tokens, then copy the access token.

Return to Cloud Shell, enter and run the following command to set your OAuth2 token as an environment variable by pasting the access token you just generated:

Set your GCP Project ID as an environment variable as follows:

Create the Cloud Storage bucket which will store your cat’s photo

Many of APIs use client-server model and adhere to the HTTP protocol. The most commonly used HTTP request methods are GET, POST, PUT, and DELETE.

  • GET request method fetches data from a server
  • PUT method updates existing data
  • POST method creates new resources
  • DELETE method removes data or resources

We use POST in our example to create new resources:

curl -X POST — data-binary @skyline.json  
-H “Authorization: Bearer $OAUTH2_TOKEN”
-H “Content-Type: application/json” “$PROJECT_ID"

Curl docs can be found at this link.

View the newly created Bucket from the Navigation menu select Storage > Browser:

Click on the 3-dot button to upload your cat’s photo to directory on cloud shell

Get the real path to the image file, then set the path and your bucket name skyline as environment variables

Check your bucket on Cloud Storage.

Click on the image “yoda.jpg” which will open in a new tab.



You just developed an understanding of how to upload a local file to cloud storage using the Cloud Storage JSON/REST API. To recap briefly, you learned about GCP APIs, the HTTP protocol and methods, and API authentication practices.

Your turn: upload your cat’s photo to cloud. If you don’t have a cat, upload your dog’s photo. If you don’t have a dog, upload your selfie. If you don’t have selfie, hmm, stop coding! Hang out with friends 🙂

read original article here