-
Notifications
You must be signed in to change notification settings - Fork 1.4k
[v2] Empty object body schema generated when using @Accept #2142
Description
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 docsActual 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: trueExpected Output (rc4 - CORRECT)
paths:
/things:
post:
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/main.CreateRequest'
description: Request
required: trueRoot 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"] = mediaTypeLater, 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.