LoginSignup
21
26

More than 5 years have passed since last update.

Go言語でRESTful APIクライアント: Qiita APIを叩いてみよう!

Posted at

この記事の目的

Go言語で Qiita API のRESTful APIを叩いてトークンを取れるようになる

Qiita APIの仕様

token取得

POST /api/v1/auth

認証: ユーザー名+パスワードによる認証

input

  • url_name (必須) String
    • Qiitaのユーザー名(twittername or githubname@github)
  • password (必須) String

response

Status: 200 OK

{
  "url_name": "yourname",
  "token": "yoursecrettoken"
}

エラー時のレスポンス

APIのリクエストに失敗したときはステータスコード400/403/404でエラーメッセージが以下の形式で返される.

{"error": "Required key `url_name` is missing."}

実装してみる

RESTful APIクライアントライブラリは github.com/jmcvetta/napping を使う。

main.go
package main

import (
    "log"
    "github.com/jmcvetta/napping"
)

func main() {
    urlName := "suin" // ここは自分のものに
    password := "p@ssW0rd" // ここは自分のものに

    // 入力JSONのフォーマットを定義 & 初期化
    input :=  struct {
        UrlName string `json:"url_name"` // JSONのキーと構造体のキーが一致しないものは、ここでマッピングする 
        Password string `json:"password"` // 同上
    } {
        urlName,
        password,
    }

    // 正常時のJSONのフォーマットを定義 & 初期化
    // Qiitaからのレスポンスには url_name も含まれるが、必要ないのでここでは定義しない
    response := struct {
        Token string
    } {}

    // エラー時のJSONのフォーマットを定義 & 初期化
    error := struct {
        Error string
    } {}

    resp, err := napping.Post("https://qiita.com/api/v1/auth", &input, &response, &error) // input, response, errorは参照を渡す

    if err != nil {
        panic(err)
    }

    log.Printf("status: %#v", resp.Status())
    log.Printf("token: %#v", response.Token)
    log.Printf("error message: %#v", error.Error)
}

実行してみる

go run main.go

結果

2013/12/11 21:07:42 status: 200
2013/12/11 21:07:42 token: "d61c32d3f02543b39d61e9b545c58d0c"
2013/12/11 21:07:42 error message: ""
21
26
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
26