Velocity

方向を定めて

APIキーを使ったGoogle APIの認証をGoで行う

f:id:tmk_0613:20190212221810p:plain

概要

まず、前提としてGoogle APIを使用するためには、リクエストを発行するクライアントが正当である事を主張するために認証が必要である。

Google APIの認証方法は3種類に大別される。(2019/02/11時点)

  1. APIキー
  2. OAuth 2.0
  3. サービスアカウント

当記事では、Google APIsが提供している各APIを利用するためのGoライブラリ google-api-go-client を利用した、APIキーを用いた認証方法を簡潔にまとめる。

github.com

準備

APIキーの用意

Google API console にアクセスし、ヘッダーから「プロジェクトの選択」をクリックする。(無い場合は新規に作成する)

Google APIs プロジェクトの選択

次に 「メニュー」 → 「認証情報」を開き、「認証情報を作成」→「APIキー」と進むと、APIキーが作成される。このAPIキーをリクエストに埋め込む事で認証が行われ、Google APIを利用することができる。

Google APIキーの発行

実装

パッケージのimport

まず、利用するAPIのパッケージをimportする。

今回は YouTube Data API を利用するので、対応するパッケージの youtube パッケージをimportしている。APIキーで認証を行う場合は、 transport パッケージも併せて必要となる。

import (
    "net/http"
    "google.golang.org/api/googleapi/transport"
    "google.golang.org/api/youtube/v3"
)

クライアントの定義

次に、HTTPクライアントに値する構造体を定義する。

developerKey := "[作成したAPIキー]"

client := &http.Client{
    Transport: &transport.APIKey{Key: developerKey},
}

transportパッケージ内で APIKey型は以下のように定義付けられている。

type APIKey struct {
    // Key is the API Key to set on requests.
    Key string

    // Transport is the underlying HTTP transport.
    // If nil, http.DefaultTransport is used.
    Transport http.RoundTripper
}

上で定義した clientTransport フィールドにAPIキーを指定した、http.Client型のポインタだ。 この事から google-api-go-client は単に httpパッケージを用いた通信処理をラップして、扱いやすくしているライブラリだという事が伺える。

APIサービスの定義

APIを利用するためにサービスを定義する。定義の際には、各API用のパッケージに定義されている New メソッドを用いる。

New メソッドの引数に先ほど定義したクライアントを指定することで、APIキーをサービス自体に埋め込んでいる。

service, err := youtube.New(client)
if err != nil {
    log.Fatalf("Error creating new YouTube client: %v", err)
}

メソッドの利用

上記で定義したサービスに定義されているメソッドを呼ぶ事で、対象のAPIに実際のリクエストを飛ばすことができる。

文章だと理解しづらいと思うので Search メソッドを利用してみる。 流れとしては、リクエストの詳細を call として定義し、Do でリクエストを飛ばしている。

query := "The Chemical Brothers - Go"
maxResults := 1

call := service.Search.List("id,snippet"). // Listメソッドを指定
    Q(query). // 検索クエリを指定
    MaxResults(maxResults) // 最大取得件数を指定
response, _ := call.Do() // 定義したリクエスト(`call`)を実行

Searchメソッドの場合、このような形式で response が返ってくる。

[]*youtube.SearchResult{
  &youtube.SearchResult{
    Etag: "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk/ZIRkyzKLO8yyOOhAO8Io-oAZJ9o\"",
    Id:   &youtube.ResourceId{
      ChannelId:       "",
      Kind:            "youtube#video",
      PlaylistId:      "",
      VideoId:         "LO2RPDZkY88",
      ForceSendFields: []string{},
      NullFields:      []string{},
    },
    Kind:    "youtube#searchResult",
    Snippet: &youtube.SearchResultSnippet{
      ChannelId:            "UC11RIQQg3bSkGtnpx9dom5g",
      ChannelTitle:         "ChemicalBrothersVEVO",
      Description:          "Explore more music from The Chemical Brothers https://ChemicalBrothers.lnk.to/essentials The new album 'Born In The Echoes' is out now. Get it on iTunes ...",
      LiveBroadcastContent: "none",
      PublishedAt:          "2015-05-04T18:30:01.000Z",
      Thumbnails:           &youtube.ThumbnailDetails{
        Default: &youtube.Thumbnail{
          Height:          90,
          Url:             "https://i.ytimg.com/vi/LO2RPDZkY88/default.jpg",
          Width:           120,
          ForceSendFields: []string{},
          NullFields:      []string{},
        },
        High: &youtube.Thumbnail{
          Height:          360,
          Url:             "https://i.ytimg.com/vi/LO2RPDZkY88/hqdefault.jpg",
          Width:           480,
          ForceSendFields: []string{},
          NullFields:      []string{},
        },
        Maxres: (*youtube.Thumbnail)(nil),
        Medium: &youtube.Thumbnail{
          Height:          180,
          Url:             "https://i.ytimg.com/vi/LO2RPDZkY88/mqdefault.jpg",
          Width:           320,
          ForceSendFields: []string{},
          NullFields:      []string{},
        },
        Standard:        (*youtube.Thumbnail)(nil),
        ForceSendFields: []string{},
        NullFields:      []string{},
      },
      Title:           "The Chemical Brothers - Go",
      ForceSendFields: []string{},
      NullFields:      []string{},
    },
    ForceSendFields: []string{},
    NullFields:      []string{},
  },
}   

YouTube Data APIに対してリクエストを発行し、レスポンスを受け取る事ができた。

まとめ

google-api-go-clientを用いて、Google APIにアクセスできるようになった。

youtubeAPIサンプルが分かりやすいので最後に置いておく。 github.com