Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify Swagger specification extensions via code?

I am trying to add custom properties into the info section of the swagger.json that gets generated. I found many articles that talk about how to add the properties in the json by prefixing them with "x-". (ex: https://swagger.io/specification/#specification-extensions)

But, I cannot find anything that shows how to do this via C# code. (Currently using .NET 5)

We currently set the standard properties like so:

options.SwaggerDoc(Swagger.Version, new OpenApiInfo
{
  Title = "Service Api",
  Version = Swagger.Version,
  Description = "This describes the routes associated with the Service Api."
});

Just to test this, I tried extending OpenApiInfo like so:

public class CustomInfo : OpenApiInfo
{
  [JsonPropertyName("x-test")]
  public String Test;
}

then altering the SwaggerDoc like so:

options.SwaggerDoc(Swagger.Version, new CustomInfo
{
  Title = "Service Api",
  Version = Swagger.Version,
  Description = "This describes the routes associated with the Service Api.",
  Test = "New Value"
});

This did not work. How can I add a custom property (specification extension) to the api info?

like image 383
ScubaSteve Avatar asked Mar 02 '26 19:03

ScubaSteve


1 Answers

I found that you can easily add the custom properties (specification extensions) to the OpenApiInfo's Extension property. You do not need to create your own classes that implement IOpenApiExtension for the value of the Dictionary. The class that came with the Swagger nuget package that I used was OpenApiString

options.SwaggerDoc(Swagger.Version, new OpenApiInfo
{
  Title = "Service Api",
  Version = Swagger.Version,
  Description = "This describes the routes associated with the Service Api.",
  Extensions = new Dictionary<string, IOpenApiExtension>
  {
    { "x-company", new OpenApiString("Company Name") },
    { "x-contact", new OpenApiString("[email protected]") }
  }
});

There are many other ready to use classes like OpenApiBoolean, OpenApiDateTime, or if you need an object, OpenApiObject. There are many others as well.

like image 153
ScubaSteve Avatar answered Mar 05 '26 12:03

ScubaSteve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!