Protobuf 如何转换为 OpenAPI V3/Swagger

1,442 阅读2分钟

简介

Protocol Buffers 是一种轻便高效的结构化数据存储格式,具有强规范、便捷和可扩展的特点 。

OpenAPI/Swagger 规范(OAS),是定义一个标准的、与具体编程语言无关的RESTful API的规范。

在Web开发中,Proto作为最初接口设计的格式,Swagger常作为接口文档提供跨编程语言沟通。这时需要将Proto文件转换为OpenAPI,本文将介绍如何将Proto文件转换为OpenAPI v3规范。

gnostic

gnostic是Google开源的一个Go命令行工具,它可以将JSON和YAML OpenAPI描述转换为等效的Protocol Buffer表示。

安装gnostic

 go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest

生成OpenAPI/Swagger

  1. 在工作目录创建一个Proto文件: greeter.proto
syntax = "proto3";

package helloworld.v1;

import "google/api/annotations.proto";

option go_package = "helloworld/api/helloworld/v1;v1";
option java_multiple_files = true;
option java_package = "dev.kratos.api.helloworld.v1";
option java_outer_classname = "HelloworldProtoV1";

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {
    option (google.api.http) = {
      get: "/helloworld/{name}"
    };
  }
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}
  1. 运行protoc 并选择optional: --openapi_out= 指定生成swagger文件
protoc --proto_path=. --openapi_out=fq_schema_naming=true,default_response=false:. greeter.proto --proto_path=./third
  1. 如果执行成功将在工作目录生成 openapi.yaml,详细如下
# Generated with protoc-gen-openapi
# https://github.com/google/gnostic/tree/master/cmd/protoc-gen-openapi

openapi: 3.0.3
info:
    title: Greeter API
    description: The greeting service definition.
    version: 0.0.1
paths:
    /helloworld/{name}:
        get:
            tags:
                - Greeter
            description: Sends a greeting
            operationId: Greeter_SayHello
            parameters:
                - name: name
                  in: path
                  required: true
                  schema:
                    type: string
            responses:
                "200":
                    description: OK
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/helloworld.v1.HelloReply'
components:
    schemas:
        helloworld.v1.HelloReply:
            type: object
            properties:
                message:
                    type: string
            description: The response message containing the greetings
tags:
    - name: Greeter

可以通过swagger editor更清晰的显示内容

1713627448666.png 更多工具参考:

openapi.yaml 转为 json 格式

可以通过swagger editor--file--convert and save as JSON 保存为json格式

1713628728374.png

小结

本文简要介绍了Protobuf和OpenAPI/Swagger的概念和特点,以及如何将Protobuf转换为OpenAPI/Swagger。为了方便浏览,可以选择OpenAPI工具,如swagger editor。

参考