Home > Software engineering >  Include format in swagger generated from C# web api
Include format in swagger generated from C# web api

Time:12-21

I've been given a sample swagger definition and been asked to create a web-api to match. (I don't have permissions to generate the API from SwaggerHub so that isnt' an option). I need my Web API to generate Swagger docs as close to the original as possible.

The existing Swagger doc includes schema definitions that include properties like this:

titleOrderId    string($uuid)
                id of the title order - not a file number
orderDate       string($date-time)
documentCount   string($int32)

In the YAML, I see the following:

enter image description here

I've created the same objects/properties in c#, but they produce the following Swagger schemas:

titleOrderId    string
orderDate       string
documentCount   string

Is there a way to specify format and description in my c# code so that I can produce the same Swagger output?

I'm working in ASP.Net Core 6.0

CodePudding user response:

There is no such thing as string($int32) in the OpenAPI specification. It should be either string if it really is a string(no matter if it's formatted as an int) or it should be integer($int32) if it is an integer.

The other two are fixed this way:

public class OrderItem {
    public Guid TitleOrderId { get; set; }
    public DateTime OrderDate { get; set; }
    public int DocumentCount { get; set; } // or change to string if it should be a string
}

UPDATE

In order to add a description, you would need to install Swashbuckle.AspNetCore.Annotations NuGet Package.

Then enable annotations in Startup:

services.AddSwaggerGen(c =>
{
   ...

   c.EnableAnnotations();
});

Then you add the description using SwaggerSchema attribute. You can also set DocumentCount to string and add int32 format param. That would break OpenAPI spec, but would do what you want:

public class OrderItem {
    [SwaggerSchema("id of the title order - not a file number")]
    public Guid TitleOrderId { get; set; }

    public DateTime OrderDate { get; set; }

    [SwaggerSchema(Format = "int32")]
    public string DocumentCount { get; set; }
}

You could also do it like this if you really wanted, but I would recommend to leave the Guid and DateTime types:

public class OrderItem {
    [SwaggerSchema("id of the title order - not a file number", Format = "uuid")]
    public string TitleOrderId { get; set; }

    [SwaggerSchema(Format = "date-time")]
    public string OrderDate { get; set; }

    [SwaggerSchema(Format = "int32")]
    public string DocumentCount { get; set; }
}
  • Related