How to add a swagger example to the fields in the asp.net core?

Viewed 455

Based on the Swagger documentation I must be able to add some examples for my class fields, something like:

enter image description here

But I can't find any way to add these examples to my classes.

2 Answers

You can enable XML Comments and then use the <example> element to define an example. Here's an example of using an <example>:

public class CompanyValidationResponse
{
    /// <example>1234</example>
    public int CompanyId { get; set; }

    /// <example>Damage, Inc</example>
    public string CompanyName { get; set; }
}

To do this first you need to add XML documentation to your class. Here is an example.

namespace WebApplication44
{
    /// <summary>
    /// Display Weather Forecast
    /// </summary>
    public class WeatherForecast
    {
        /// <summary>
        /// Date of the weather
        /// </summary>
        public DateTime Date { get; set; }

        /// <summary>
        /// Temperature in Degree Celesuis
        /// </summary>
        public int TemperatureC { get; set; }
        /// <summary>
        /// Temperature in Fahrenheit
        /// </summary>
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        /// <summary>
        /// Summary of the Weather. It can be "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        /// </summary>
        public string? Summary { get; set; }
    }
}

Next, you need to enable the Documentation File > Generate a File containing API documentation option in the Project Properties in Visual Studio - No need to change the location.

Finally, modify the swagger generation code like this.

var xmlDoc = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "xml");
builder.Services.AddSwaggerGen(options => options.IncludeXmlComments(xmlDoc, true));

Then you will be able to see the Open API doc like this.

Open API with Examples

Related