Search code examples
.net-coreswaggerasp.net-core-webapiswagger-ui

Add example value to swagger UI for parameters


Is there any way in .Net core to include Example value to parameter of an action method in the Swagger UI. The same way the example value is displayed for response/request.

There doesn't seem any direct way such as SwaggerRequestExample in .Net core so that example value can be displayed for Parameters.

Can someone help me with initial solution or any link with which I can start.

I am looking for output something like below.

enter image description here

This is model object

public class Vehicle
{
        public long Id { get; set; }
        public string VehicleName { get; set; }
        public int Price { get; set; }
}

This is post method

 [HttpPost]
 public void Post(int id, [FromBody] Vehicle val)
 {

 }

This would display ID as a parameter but Vehicle model doesn't show up in Parameters list. I want it to display as an example value. I have also configured following in startup file c.IncludeXmlComments(xmlPath);


Solution

  • By default, Swashbuckle generates and exposes Swagger JSON in version 3.0 of the specification—officially called the OpenAPI Specification. To support backwards compatibility, you can opt into exposing JSON in the 2.0 format instead. This 2.0 format is important for integrations such as Microsoft Power Apps and Microsoft Flow that currently support OpenAPI version 2.0. To opt into the 2.0 format, set the SerializeAsV2 property in Startup.Configure:

       ...
       // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger(c =>
        {
            c.SerializeAsV2 = true;
        });
      ...
    

    Before

    {
      "openapi": "3.0.1",
      "info": {
        "title": "SwaggerApplication",
        "version": "1.0"
      },...
    

    enter image description here

    After

    {
      "swagger": "2.0",
      "info": {
        "title": "SwaggerApplication",
        "version": "1.0"
      }, ...
    

    enter image description here