If you are using the OpenAPI standard for your Rest API’s on .NET Core you will probably be familiar with the Swagger tools that enable you to quickly generate definitions for your Web API endpoints. With a few lines of code you can enable Swagger and Swagger-UI using the awesome Swashbuckle project.

This is perfect when your have Web API controllers that you can decorate with attributes to describe your Rest API and document how it should be used but in some cases, for example when you are using a dynamically created series of endpoints, it may be useful to create your swagger definition files manually.

To do this, there is an excellent project from Microsoft on GitHub called OpenAPI.NET. The OpenAPI.NET SDK contains a useful object model for OpenAPI documents in .NET along with common serializers to extract raw OpenAPI JSON and YAML documents from the model. You can get the package directly from Nuget here.

A valid Swagger document written in  C# looks like

var document = new OpenApiDocument
  {
      Info = new OpenApiInfo
      {
          Version = "1.0.0",
          Title = "Swagger Petstore (Simple)",
      },
      Servers = new List<OpenApiServer>
      {
          new OpenApiServer { Url = "http://petstore.swagger.io/api" }
      },
      Paths = new OpenApiPaths
      {
          ["/pets"] = new OpenApiPathItem
          {
              Operations = new Dictionary<OperationType, OpenApiOperation>
              {
                  [OperationType.Get] = new OpenApiOperation
                  {
                      Description = "Returns all pets from the system that the user has access to",
                      Responses = new OpenApiResponses
                      {
                          ["200"] = new OpenApiResponse
                          {
                              Description = "OK"
                          }
                      }
                  }
              }
          }
      }
  };

To generate the swagger definition file for use with tools such as Swagger-UI you can now serialise the document object.

using (var  outputString  =  new  StringWriter())
{
  var  writer  =  new  OpenApiJsonWriter(outputString);
  document.SerializeAsV3(writer);
  await  File.WriteAllTextAsync("c:/temp/swagger.json", outputString.ToString());
}

The generated JSON file will contain the valid Swagger document ready for use in your Swagger compliant tools

{
  "openapi": "3.0.1",
  "info": {
  	"title": "Swagger Petstore (Simple)",
  	"version": "1.0.0"
  },
  "servers": [
  	{
  		"url": "http://petstore.swagger.io/api"
  	}
  ],
  "paths": {
  	"/pets": {
  		"get": {
  		"description": "Returns all pets from the system that the user has access to",
  		"responses": {
  			"200": {
  				"description": "OK"
  				}
  			}
  		}
  	}
  }
}

You can test your newly generated Swagger JSON file by pasting the code into the online tool Swagger Editor that will validate your file, and if successful with show the interactive Swagger UI that will be generated from your definition

To serialize a Swagger JSON file back to an OpenApiDocument, we can use the one of the OpenApi Readers . Note these are available in a seperate package, available from NuGet. Once the package has been added to your project, you can use a reader, such as the OpenApiStringReader to parse the valid JSON file back into an OpenApiDocument as follows

var  json  =  File.ReadAllText("c:/temp/swagger.json");

OpenApiDocument  document  =  new  OpenApiStringReader().Read(json, out  var  diagnostic);

Now you can interact directly with the Swagger object model again to manipulate your schemas.