diff --git a/huma.go b/huma.go index a80bf2c2..8d0b952c 100644 --- a/huma.go +++ b/huma.go @@ -1544,6 +1544,12 @@ func setRequestBodyFromBody(op *Operation, registry Registry, fBody reflect.Stru } s := SchemaFromField(registry, fBody, hint) op.RequestBody.Content[contentType].Schema = s + + // Surface the `example` tag from the Body field on the media type, as + // examples set alongside a schema `$ref` are ignored by many tools. + if s != nil && len(s.Examples) > 0 && op.RequestBody.Content[contentType].Example == nil && len(op.RequestBody.Content[contentType].Examples) == 0 { + op.RequestBody.Content[contentType].Example = s.Examples[0] + } } } diff --git a/huma_test.go b/huma_test.go index 5d35f4c1..302301cd 100644 --- a/huma_test.go +++ b/huma_test.go @@ -1274,6 +1274,29 @@ func TestFeatures(t *testing.T) { assert.Equal(t, http.StatusBadRequest, resp.Code) }, }, + { + Name: "request-body-example-promoted-to-media-type", + Register: func(t *testing.T, api huma.API) { + huma.Register(api, huma.Operation{ + Method: http.MethodPut, + Path: "/body", + }, func(ctx context.Context, input *struct { + Body struct { + Name string `json:"name"` + } `example:"{\"name\": \"world\"}"` + }) (*struct{}, error) { + return nil, nil + }) + content := api.OpenAPI().Paths["/body"].Put.RequestBody.Content["application/json"] + // The example from the Body field is surfaced on the media + // type, since examples alongside a schema $ref are ignored + // by many tools. + require.NotNil(t, content.Example) + }, + Method: http.MethodPut, + URL: "/body", + Body: `{"name": "world"}`, + }, { Name: "request-body-nameHint", Register: func(t *testing.T, api huma.API) {