OpenAPI.NET icon indicating copy to clipboard operation
OpenAPI.NET copied to clipboard

Add Builder to simplify openapi document object construction

Open jkone27 opened this issue 4 years ago • 4 comments

A regular C# builder pattern would help a lot in many scenarios. Building an object now is very complex...

Builder pattern is also the "de facto" in Aspnetcore.. so would make sense to expose a similar api

var openApiDocumentBuilder = new OpenApiDocumentBuilder()
     .WithServers(...)
     .WithOperation(...)
     .WithOperation(...)
     .WithSchema(...);
//... etc


var openApiDocument = openApiDocumentBuilder.Build();
     

jkone27 avatar Dec 23 '21 14:12 jkone27

Agreed, building it is clunky. Would you mind starting a discussion thread on ways that we could improve construction?

darrelmiller avatar Jan 23 '22 02:01 darrelmiller

I very nice project i saw in the F# space is this one (it uses F# Computation Expressions CEs for the builder pattern), but probably with extension methods something much similar can be obtained.. (or maybe also the F# part could be included in the "official one" for the F# api)

https://github.com/akhansari/FSharp.OpenApi

let document =
    apiDocument {
        info (apiInfo {
            version "1.0.0"
            title "Swagger Petstore (Simple)"
        })
        servers [
            apiServer {
                url "http://petstore.swagger.io/api"
            }
        ]
        paths [
            "/pets", apiPathItem {
                operations [
                    OperationType.Get, apiOperation {
                        description "Returns all pets from the system that the user has access to"
                        responses [
                            HttpStatusCode.OK, apiResponse {
                                description "OK"
                            }
                        ]
                    }
                ]
            }
        ]
    }

let outputString =
    document.Serialize (OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json)

i guess the C# counterpart would be like

var document = 
    OpenApi.Builder()
          .WithInfo(....)
          .WithServers(...)
          .WithPaths(...)
          .Build();
          
  var openApiJsonV3String = document.Serialize (OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json);
          

jkone27 avatar Jan 24 '22 09:01 jkone27

I came across this issue while drafting a proposal for a new API in ASP.NET Core that builds on top of Microsoft.OpenAPI (see https://github.com/dotnet/aspnetcore/issues/44192).

IMO, it would be really neat to have a builder-style pattern for an OpenAPI document.

captainsafia avatar Sep 26 '22 22:09 captainsafia