Roman Gelembjuk
Roman Gelembjuk

Reputation: 2005

Google Cloud Vision API. Golang . How to get API JSON

I use Google Cloud Vision API with the Go SDK. In some cases I don't want to use Golang structures to read API results, I just want to get full JSON response of an API call. For example,

// detectDocumentText gets the full document text from the Vision API for an
// image at the given file path.
func detectDocumentTextURI(w io.Writer, file string) error {
        ctx := context.Background()

        client, err := vision.NewImageAnnotatorClient(ctx)
        if err != nil {
                return err
        }

        image := vision.NewImageFromURI(file)
        annotation, err := client.DetectDocumentText(ctx, image, nil)
        if err != nil {
                return err
        }

        if annotation == nil {
                fmt.Fprintln(w, "No text found.")
        } else {
                fmt.Fprintf(w, "API Response %s", ...JSON...)
        }

        return nil
}

How can I get that JSON from annotation structure? Is it possible?

Upvotes: 1

Views: 580

Answers (1)

Tyler B
Tyler B

Reputation: 1698

Is there something in particular you're looking for in the JSON? You could pretty-print the response object as JSON, if you trying to explore what's returned:

json, err := json.MarshalIndent(annotation, "", "  ")
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(json))

It's a bit difficult to get the raw JSON response from this call because under the hood it's using gRPC, not JSON. If you follow the client code for a bit (it's open source), you'll eventually get to https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/vision/apiv1/image_annotator_client.go#L142:

func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) 

You can see that function build up the request, send it, and return the response (the same proto response you get from calling the original function, restricted to res.FullTextAnnotation). See https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/vision/apiv1/client.go#L109.

Upvotes: 3

Related Questions