devlog

【Go】kin-openapi で openapi.yaml を出力する

2023-08-21

Go言語で OpenAPI を記述するとき kin-openapi が便利でした。
ざっくり使い方をメモします。

kin-openapi

kin-openapi を go get します

go get github.com/getkin/kin-openapi

また yamlファイルの出力のために go-yaml を使います

go get github.com/go-yaml/yaml

 

OpenAPI を出力する

API仕様を最低限記述して、ひとまずyamlファイルへと出力してみます。

  • OpenAPI をいちから記述するには openapi3.T という構造体を用います
  • 構造体のフィールドを埋めていきましょう
  • 最後に yaml.Marshal() し openapi.yaml を出力します
package main import ( "os" "github.com/getkin/kin-openapi/openapi3" "github.com/go-yaml/yaml" ) func main() { // API仕様の記述 spec := openapi3.T{} spec.OpenAPI = "3.0.3" spec.Info = &openapi3.Info{ Title: "Sample API", Version: "0.1.0", } // yaml へ specYaml, err := yaml.Marshal(spec) if err != nil { return } // ファイル作成 f, err := os.Create("openapi.yaml") if err != nil { return } defer f.Close() f.Write(specYaml) }

コードを実行します。

go run .

openapi.yaml が出力されます。中身は次のようになりました。

openapi: 3.0.3 info: title: Sample API version: 0.1.0 paths: {}

エンドポイントを定義する

続いて、OpenAPIのPathを書いていきます。
ここではサンプルとして POST /notes というエンドポイントを用います。

また、kin-openapi/openapi3gen を用いて、struct からスキーマを生成します。

package main import ( "os" "github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3gen" "github.com/go-yaml/yaml" ) func main() { // API仕様の記述 spec := openapi3.T{} spec.OpenAPI = "3.0.3" spec.Info = &openapi3.Info{ Title: "Sample API", Version: "0.1.0", } spec.Components = &openapi3.Components{ Schemas: openapi3.Schemas{}, } spec.Paths = openapi3.Paths{} // リクエストボディ type Note struct { Name string `json:"name"` Description string `json:"description"` } // struct から openapi3.SchemaRef を作成 noteSchemaRef, _ := openapi3gen.NewSchemaRefForValue(&Note{}, nil) // スキーマを定義 spec.Components.Schemas["note"] = noteSchemaRef // エンドポイント operation := openapi3.Operation{} operation.Summary = "ノート作成" operation.RequestBody = &openapi3.RequestBodyRef{ Value: &openapi3.RequestBody{ Content: openapi3.Content{ "application/json": &openapi3.MediaType{ Schema: &openapi3.SchemaRef{ // スキーマの名前を入れる(ref) Ref: "#/components/schemas/note", }, }, }, }, } spec.Paths["/notes"] = &openapi3.PathItem{} spec.Paths["/notes"].SetOperation("POST", &operation) // openapi.yaml の出力 // (略) }

次のようなファイルが出力されました。

openapi: 3.0.3 info: title: Sample API version: 0.1.0 paths: /notes: post: summary: ノート作成 requestBody: content: application/json: schema: $ref: '#/components/schemas/note' responses: {} components: schemas: note: type: object properties: description: type: string name: type: string

以上です

  • 作成日
    2023-08-21
  • 更新日
    2023-10-02