Google’s Cloud Platform documentation is top of the line. Even with the documentation though, it took me some time to figure out how to use the Cloud Vision API from a Go application running on a Compute Engine instance. All the right information is there, but it’s scattered. Below I’ve compiled this information into a few steps.

Authenticating with the Cloud Vision API involves more setup than the Cloud Datastore, Cloud Pub/Sub and Cloud Storage. The client libraries for the latter use  Google Application Default Credentials and “just work” when running on a Compute Engine instance. In order to authenticate with the Cloud Vision API, you need to create a service account key and instruct the client library to use that key when sending API requests. See Authenticating to the Cloud Vision API for more details.

Prerequisites

Steps

  1. Enable the Cloud Vision API for your project: https://console.cloud.google.com/apis/api/vision.googleapis.com/overview

  2. If you haven’t already, create a JSON key for the service account running the Compute Engine instance: https://console.cloud.google.com/iam-admin/serviceaccounts/project. Click the dropdown beside the service account, click Create Key and select the JSON key type.

  3. Copy the key JSON file to your Compute Engine instance

  4. When creating the Vision API client in Go, provide the service account file with option.WithServiceAccountFile("/path/to/key.json"):

    visionClient, err := vision.NewImageAnnotatorClient(ctx, option.WithServiceAccountFile("/path/to/key.json"))
        if err != nil {
            return nil, nil, errors.Wrap(err, "Error creating vision client")
        }