Tarmil / FSharp.SystemTextJson

System.Text.Json extensions for F# types
MIT License
325 stars 44 forks source link

Support OpenApi Schema generation #46

Open Swoorup opened 4 years ago

Swoorup commented 4 years ago

It would be nice if we could add OpenApi 3.0 schema generation. So F# types could directly be exposed in REST models. Its possible to override schema using SchemaFilter in Swashbuckle.

Swoorup commented 4 years ago

I am hacking out a initial implementation like this:

        interface ISchemaFilter with
            member this.Apply (schema: OpenApiSchema, context: SchemaFilterContext) =
                let objType = context.Type
                if objType |> IsUnion then
                    schema.Properties <- Dictionary()

                    let cases =
                        GetUnionCases objType
                        |> Seq.map (fun field ->
                            let case = OpenApiSchema()
                            case.Title <- field.Key
                            case
                            )
                        |> BCLConverters.seqToList

                    let obj = OpenApiSchema()
                    obj.Type <- "object"
                    obj.OneOf <- cases

                    let caseProp = OpenApiSchema(Type = "string")

                    schema.Properties.Add("Case", caseProp)
                    schema.Properties.Add("Fields", obj)
                    ()

Which generates the following: image

However the code is duplicated. Any ideas so it can be unified across the serializer as well as openapi generation?

xperiandri commented 1 year ago

@Swoorup maybe it should go to Microsoft.OpenAPI package?