🍎
【Go】外部APIを叩いてみる
はじめに
Laravelで外部APIを叩くときはGuzzleを使いますが、Goではどのように外部APIを叩けるのか知らなかったので調べました。
調べたものを簡潔にまとめます。
実装
今回使用する外部API
-
Agify API
- 名前や国名から年齢を予測するAPI
- 名前を複数指定することもできる
外部APIの叩き方
-
http.Get("外部APIエンドポイント")
- httpパッケージに存在するGETメソッドを活用
- *Response型のrespとerror型のerrを返す
実装内容
main.go
package main
import (
"encoding/json"
"io"
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.GET("/estimation", func(c echo.Context) error {
resp, err := http.Get("https://api.agify.io?name=taro&country_id=JP")
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
return c.JSON(http.StatusOK, json.RawMessage(body))
})
e.Logger.Fatal(e.Start(":8080"))
}
注意点
HTTPコネクションが開いたままになるので、deferを用いてコネクションが終了するようにする
結果
ターミナル
curl http://localhost:8080/estimation
↓
{"count":345,"name":"taro","age":68,"country_id":"JP"}
まとめ
外部APIを叩く際は、http.Get("外部APIエンドポイント") を使う!
Discussion