Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Include format in swagger generated from C# web api

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 {
    public Guid TitleOrderId { get; set; }
    public DateTime OrderDate { get; set; }

    [SwaggerSchema("id of the title order - not a file number", Format = "int32")]
    public string DocumentCount { get; set; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading