Omar
Omar

Reputation: 861

Generate response example values using swagger with GRPC

I'm generating swagger json file using protoc-gen-swagger with gRPC service. The output json is being generated with empty response examples, I want to add response examples to the definition so it gets automatically populated in the generated json.

This is my current definition.

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;
}

When I generate the swagger file using the command

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

I get a swagger file with this user object definition

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

What I want is to generate it with example values like this:

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

Upvotes: 1

Views: 2207

Answers (1)

Omar
Omar

Reputation: 861

Found the answer to this here: https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto#L197

Simple by adding grpc.gateway.protoc_gen_swagger.options.openapiv2_schema as an option to the message.

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;
}

Upvotes: 5

Related Questions