Search code examples
goopenapi-generatorgo-gin

Fizz OpenAPi generator for Gin is renaming types


I have created a simple API written in Gin. I used Fizz to generate an OpenApi 3 specification. Here is my POST endpoint:

// Sets user route group
func UserRoute(grp *fizz.RouterGroup) {

    // create new user
    grp.POST("", []fizz.OperationOption{
        fizz.Summary("Creates new user and sends verification mail."),
        ...
    }, tonic.Handler(handlers.CreateUser, 201))
}

And here is the handler method:

// Creates new user
func CreateUser(c *gin.Context, register *models.Register) error {
    ...

    return nil
}

The problem is that in the generated JSON specification the "Register" model shows as "CreateUserInput":

enter image description here

Is there any way to fix it or is this normal?


Solution

  • According to the implementation, the schema name is generated by this statement: name := strings.Title(op.ID) + "Input" (see line 23 below):

     1  // setOperationParams adds the fields of the struct type t
     2  // to the given operation.
     3  func (g *Generator) setOperationParams(op *Operation, t, parent reflect.Type, allowBody bool, path string) error {
     4      if t.Kind() != reflect.Struct {
     5          return errors.New("input type is not a struct")
     6      }
     7      if err := g.buildParamsRecursive(op, t, parent, allowBody); err != nil {
     8          return err
     9      }
    10      // Input fields that are neither path- nor query-bound
    11      // have been extracted into the operation's RequestBody
    12      // If the RequestBody is not nil, give it a name and
    13      // move it to the openapi spec's components/schemas section
    14      // Replace the RequestBody's schema with a reference
    15      // to the named schema in components/schemas
    16      if op.RequestBody != nil {
    17          mt := tonic.MediaType()
    18          if mt == "" {
    19              mt = anyMediaType
    20          }
    21          sch := op.RequestBody.Content[mt].Schema
    22          if sch != nil {
    23              name := strings.Title(op.ID) + "Input"
    24              g.api.Components.Schemas[name] = sch
    25              op.RequestBody.Content[mt].Schema = &SchemaOrRef{Reference: &Reference{
    26                  Ref: componentsSchemaPath + name,
    27              }}
    28          }
    29      }
    

    You can customize the operation ID with fizz.ID, but there is no way to remove the Input suffix. You need to fork the repository and modify the implementation if you really want to generate the schema name differently.