使用服务帐户从Google REST API获取数据

问题描述 投票:0回答:1

我想从API获取信息(数据)并显示它。使用API​​从Big Query获取数据。

目前,我已经编写了可能假设从API显示信息的代码,但我不确定如何使用服务帐户作为环境。

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

    func main() {

        response, err := http.Get("https://www.googleapis.com/bigquery/v2/projects/PROJECT_ID/queries/JOB_ID")
        if err != nil {
            fmt.Printf("%s", err)
            os.Exit(1)
        } else {
            defer response.Body.Close()
            contents, err := ioutil.ReadAll(response.Body)
            if err != nil {
                fmt.Printf("%s", err)
                os.Exit(1)
            }
            fmt.Printf("%s\n", string(contents))
        }
    }

预期的结果应该只是显示来自API的数据,然后我需要创建一个API,无需使用参数进行身份验证即可访问(如GET方法)

附:这是API的链接 - https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/getQueryResults

go google-api google-bigquery google-authentication
1个回答
2
投票

如果您查看文档,您会注意到它的统计信息Jobs: getQueryResults它表明您调用的方法要求您使用以下范围之一进行身份验证。

enter image description here

您尝试访问的数据是私有用户数据,您必须对其进行身份验证才能访问私有用户数据。您似乎没有尝试以任何方式进行身份验证。

您创建的服务帐户凭据应在您的代码中用于向Google发送授权请求

您可以在此处找到有关如何使用服务帐户进行身份验证的一些信息。 introduction to authentication

启用凭据

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

// Sample bigquery-quickstart creates a Google BigQuery dataset.
package main

import (
        "fmt"
        "log"

        // Imports the Google Cloud BigQuery client package.
        "cloud.google.com/go/bigquery"
        "golang.org/x/net/context"
)

func main() {
        ctx := context.Background()

        // Sets your Google Cloud Platform project ID.
        projectID := "YOUR_PROJECT_ID"

        // Creates a client.
        client, err := bigquery.NewClient(ctx, projectID)
        if err != nil {
                log.Fatalf("Failed to create client: %v", err)
        }

        // Sets the name for the new dataset.
        datasetName := "my_new_dataset"

        // Creates the new BigQuery dataset.
        if err := client.Dataset(datasetName).Create(ctx, &bigquery.DatasetMetadata{}); err != nil {
                log.Fatalf("Failed to create dataset: %v", err)
        }

        fmt.Printf("Dataset created\n")
}
© www.soinside.com 2019 - 2024. All rights reserved.