diff --git a/huma.go b/huma.go index 91b35926..b2c66949 100644 --- a/huma.go +++ b/huma.go @@ -1024,16 +1024,17 @@ func setRequestBodyFromBody(op *Operation, registry Registry, fBody reflect.Stru if c := fBody.Tag.Get("contentType"); c != "" { contentType = c } - hint := getHint(inputType, fBody.Name, op.OperationID+"Request") - if nameHint := fBody.Tag.Get("nameHint"); nameHint != "" { - hint = nameHint - } - s := SchemaFromField(registry, fBody, hint) if op.RequestBody.Content[contentType] == nil { op.RequestBody.Content[contentType] = &MediaType{} } - op.RequestBody.Content[contentType].Schema = s - + if op.RequestBody.Content[contentType].Schema == nil { + hint := getHint(inputType, fBody.Name, op.OperationID+"Request") + if nameHint := fBody.Tag.Get("nameHint"); nameHint != "" { + hint = nameHint + } + s := SchemaFromField(registry, fBody, hint) + op.RequestBody.Content[contentType].Schema = s + } } type rawBodyType int diff --git a/huma_test.go b/huma_test.go index a30e87d0..c5d40c4f 100644 --- a/huma_test.go +++ b/huma_test.go @@ -655,11 +655,6 @@ func TestFeatures(t *testing.T) { { Name: "request-body-examples", Register: func(t *testing.T, api huma.API) { - schema := &huma.Schema{ - Type: huma.TypeObject, - Properties: map[string]*huma.Schema{"name": {Type: huma.TypeString}}, - } - huma.Register(api, huma.Operation{ Method: http.MethodPut, Path: "/body", @@ -667,7 +662,6 @@ func TestFeatures(t *testing.T) { Description: "A description", Content: map[string]*huma.MediaType{ "application/json": { - Schema: schema, Examples: map[string]*huma.Example{ "Example 1": { Summary: "Example summary", @@ -889,6 +883,40 @@ func TestFeatures(t *testing.T) { URL: "/body", Body: `{"name": "Name"}`, }, + { + Name: "request-body-custom-schema", + Register: func(t *testing.T, api huma.API) { + api.OpenAPI().Components.Schemas.Map()["Dummy"] = &huma.Schema{ + Type: huma.TypeObject, + Properties: map[string]*huma.Schema{ + "name": {Type: huma.TypeString}, + }, + } + huma.Register(api, huma.Operation{ + Method: http.MethodPut, + Path: "/body", + RequestBody: &huma.RequestBody{ + Content: map[string]*huma.MediaType{ + "application/json": { + Schema: &huma.Schema{ + Ref: "#/components/schemas/Dummy", + }, + }, + }, + }, + }, func(ctx context.Context, input *struct { + Body struct { + Name string `json:"name"` + } + }) (*struct{}, error) { + return nil, nil + }) + assert.Equal(t, "#/components/schemas/Dummy", api.OpenAPI().Paths["/body"].Put.RequestBody.Content["application/json"].Schema.Ref) + }, + Method: http.MethodPut, + URL: "/body", + Body: `{"name": "Name"}`, + }, { Name: "request-body-embed-struct", Register: func(t *testing.T, api huma.API) {