gnosticでOpenAPIをProtocol Buffersに変換する

gnosticgnostic-grpcを使えばOpenAPIの.yaml(.json)を.protoに変換できる。

github.com

github.com

1. gnosticをインストールする

go install github.com/google/gnostic@latest

2. gnostic-grpcをインストールする

git clone https://github.com/google/gnostic-grpc
cd gnostic-grpc
./COMPILE-PROTOS.sh
./plugin-creation.sh

※ protocコマンドがないとエラーになるので Protocol Buffer Compiler Installation | gRPC あたりを参考にインストールしておく必要がある。

3. 変換する

gnostic --grpc-out=proto openapi.yaml

前回の記事で生成した以下のyamlは、

openapi: 3.0.3
info:
  description: Foo API Document.
  title: Foo API
  version: "1.0"
paths:
  /foo:
    post:
      operationId: PostFoo
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PostFooRequest'
      responses:
        "201":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Foo'
          description: Created
        "400":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
          description: Bad Request
  /foo/{id}:
    get:
      operationId: GetFoo
      parameters:
      - in: path
        name: id
        required: true
        schema:
          type: string
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Foo'
          description: OK
        "404":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
          description: Not Found
components:
  schemas:
    ErrorResponse:
      properties:
        code:
          type: string
        message:
          type: string
      type: object
    Foo:
      properties:
        data:
          type: string
        id:
          type: string
      type: object
    PostFooRequest:
      properties:
        data:
          type: string
      type: object

次のようなprotoになる。

  • proto/openapi.proto
syntax = "proto3";

package openapi;

import "google/api/annotations.proto";

import "google/protobuf/descriptor.proto";

import "google/protobuf/empty.proto";

option go_package = ".;openapi";

message PostFooRequest {
  string data = 1;
}

//PostFooParameters holds parameters to PostFoo
message PostFooRequest {
  PostFooRequest post_foo_request = 1;
}

//GetFooParameters holds parameters to GetFoo
message GetFooRequest {
  string id = 1;
}

service Openapi {
  rpc PostFoo ( PostFooRequest ) returns ( google.protobuf.Empty ) {
    option (google.api.http) = { post:"/foo" body:"post_foo_request"  };
  }

  rpc GetFoo ( GetFooRequest ) returns ( google.protobuf.Empty ) {
    option (google.api.http) = { get:"/foo/{id}"  };
  }
}

※ OpenAPIの構成によっては変換できない場合がある。
 また、OpenAPI 3.1には対応していない。