From 1507eb863e5fce9379cdfcb9bb048697749ed4cd Mon Sep 17 00:00:00 2001 From: Henning Surmeier Date: Thu, 25 Sep 2025 11:29:15 +0200 Subject: [PATCH] add formats to openapi3 numeric types This was already implemented for openapi31 in https://github.com/swaggest/openapi-go/pull/140 --- openapi3/example_test.go | 3 ++- openapi3/reflect.go | 16 ++++++++++++++++ openapi3/reflect_test.go | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/openapi3/example_test.go b/openapi3/example_test.go index eac3617..e4ca7f9 100644 --- a/openapi3/example_test.go +++ b/openapi3/example_test.go @@ -244,7 +244,7 @@ paths: schema: type: string content: - application/json: + application/json: schema: $ref: "#/components/schemas/Pets" default: @@ -585,6 +585,7 @@ func ExampleReflector_AddOperation_queryObject() { // type: string // type: object // quux: + // format: double // type: number // type: object // Openapi3TestJsonFilter: diff --git a/openapi3/reflect.go b/openapi3/reflect.go index c422c74..03603a7 100644 --- a/openapi3/reflect.go +++ b/openapi3/reflect.go @@ -26,6 +26,22 @@ func NewReflector() *Reflector { r := &Reflector{} r.SpecEns() + r.DefaultOptions = append(r.DefaultOptions, jsonschema.InterceptSchema(func(params jsonschema.InterceptSchemaParams) (stop bool, err error) { + // See https://spec.openapis.org/oas/v3.0.0.html#data-types. + switch params.Value.Kind() { //nolint // Not all kinds have formats defined. + case reflect.Int64: + params.Schema.WithFormat("int64") + case reflect.Int32: + params.Schema.WithFormat("int32") + case reflect.Float32: + params.Schema.WithFormat("float") + case reflect.Float64: + params.Schema.WithFormat("double") + } + + return false, nil + })) + return r } diff --git a/openapi3/reflect_test.go b/openapi3/reflect_test.go index bfc7dd2..55daaad 100644 --- a/openapi3/reflect_test.go +++ b/openapi3/reflect_test.go @@ -1086,7 +1086,7 @@ func TestReflector_AddOperation_defName(t *testing.T) { "paths":{ "/foo":{ "post":{ - "parameters":[{"name":"bar","in":"header","schema":{"type":"number"}}], + "parameters":[{"name":"bar","in":"header","schema":{"type":"number","format":"double"}}], "requestBody":{ "content":{ "application/json":{"schema":{"$ref":"#/components/schemas/Openapi3TestReqJSON"}},