【问题标题】:Generate response example values using swagger with GRPC使用 swagger 和 GRPC 生成响应示例值
【发布时间】:2020-07-08 10:46:50
【问题描述】:

我正在使用 protoc-gen-swagger 和 gRPC 服务生成 swagger json 文件。使用空响应示例生成输出 json,我想将响应示例添加到定义中,以便它自动填充到生成的 json 中。

这是我目前的定义。

service UserService {
  rpc GetUser (GetUserRequest) returns (UserResponse){
    option (google.api.http) = {
      get: "/api/v1/user/{username}"
      response_body: "*"
    };
    option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = {
      description: "Returns user object";
      operation_id: "get_user";
      summary: "Get User";
    };
  }
}

message GetUserRequest {
  string username = 1;
}

message UserResponse {
  User user = 1;
}

message User {
  string first_name = 1;
  string last_name = 2;
  string username = 3;
}

当我使用命令生成 swagger 文件时

protoc -I ${PROTOPATH} \
           -I $GOPATH/src \
           --swagger_out=logtostderr=true:${OUT_PATH}

我得到一个带有这个用户对象定义的 swagger 文件

"User": {
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "username": {
      "type": "string"
    },
  }
}

我想要的是用这样的示例值生成它:

"User": {
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string",
      "example": "Adam"
    },
    "last_name": {
      "type": "string",
      "example": "Smith"
    },
    "username": {
      "type": "string",
      "example": "asmith79"
    },
  }
}

【问题讨论】:

    标签: swagger grpc openapi swagger-codegen grpc-go


    【解决方案1】:

    在这里找到答案:https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto#L197

    只需将grpc.gateway.protoc_gen_swagger.options.openapiv2_schema 作为选项添加到消息中即可。

    import "protoc-gen-swagger/options/annotations.proto";
    
    message User {
      option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = {
        example: { value: '{ "first_name": "Adam", "last_name":"Smith", "username":"asmith79"}' }
      };
      string first_name = 1;
      string last_name = 2;
      string username = 3;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2015-12-02
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2021-10-08
      • 2018-08-22
      相关资源
      最近更新 更多