Skip to content

[v2] Empty object body schema generated when using @Accept #2142

@kreed

Description

@kreed

Summary

When using @Accept json with @Param body in swaggo v2.0.0-rc5, the generated OpenAPI 3.1 spec incorrectly wraps the request body schema in a oneOf with an empty object schema.

Reproduction

Code

package main

// @title Bug Repro API
// @version 1.0
// @BasePath /api

type CreateRequest struct {
	Name  string `json:"name"`
	State string `json:"state"`
}

type Response struct {
	ID int `json:"id"`
}

// CreateThing creates a thing
// @Summary Create thing
// @Accept json
// @Produce json
// @Param body body CreateRequest true "Request"
// @Success 200 {object} Response
// @Router /things [post]
func CreateThing() {}

func main() {}

Generate with rc5

go run github.com/swaggo/swag/v2/cmd/swag@v2.0.0-rc5 init --v3.1 -g main.go -o docs

Actual Output (rc5 - INCORRECT)

paths:
  /things:
    post:
      requestBody:
        content:
          application/json:
            schema:
              oneOf:
              - type: object
              - $ref: '#/components/schemas/main.CreateRequest'
                description: Request
                summary: body
        description: Request
        required: true

Expected Output (rc4 - CORRECT)

paths:
  /things:
    post:
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/main.CreateRequest'
        description: Request
        required: true

Root Cause

In operationv3.go, when @Accept json is processed, it initializes the media type with an empty schema:

// In fillRequestBody or similar
mediaType := spec.NewMediaType()
// This creates mediaType.Spec.Schema with an empty object
o.RequestBody.Spec.Spec.Content["application/json"] = mediaType

Later, when @Param body is processed, it checks if mediaType.Spec.Schema != nil. Since the schema was already initialized (albeit empty), it creates a oneOf to combine the existing empty schema with the body param schema.

Workaround

Remove @Accept json annotations from handlers that have @Param body. When @Param body is present without @Accept, swaggo defaults to application/json content type, so this doesn't change the generated API spec.

Impact

This breaks code generators like ogen that expect a direct $ref to the schema, not a oneOf with an empty object.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions