schweppes0x
schweppes0x

Reputation: 320

Swagger/OpenApi Model Example Value

I am trying to insert my own values within my Swagger/OpenApi, currently in the Model Example Value I have the following values:

Current situation

The desired situation is as shown below :

enter image description here

I've looked into it and tried multiple methods to achive this, for example I tried adding XMLComments like this:

first method

However this does not work. Then I tried to use the MapType function which provides this functionality, I've done this with the following code:

c.MapType<Student>(() => new Schema()
                    {
                        example = new Student()
                        {
                            StudentName = "John Doe",
                            Age = 28
                        }
                    });

However, when I try it this way, I get the following result: Result

Any way to fix this ?

Upvotes: 4

Views: 6330

Answers (2)

schweppes0x
schweppes0x

Reputation: 320

The method I used and which resolved my issue was the following:

Within the Swagger configuration:

.EnableSwagger("/swagger", c=> {
    c.SchemaFilter<SwaggerExamples>();
})

and then within SwaggerExamples.cs :

using Swashbuckle.Swagger;

public class SwaggerExamples : ISchemaFilter 
{
   public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
           if(type == typeof(Student))
               {
                   schema.example = new Student
                   {
                       StudentName = "John",
                       Age = 28
                   };
               }
        }
}

This resulted in the expected values shown in the image in my original question.

Upvotes: 2

hsn-mnj
hsn-mnj

Reputation: 1408

Use NuGet Package Swashbuckle.AspNetCore.Filters as follow:

Add your default model (the default value which you intend to be shown in swagger) as follow:

public class StudentDtoDefault : IExamplesProvider<StudentDto>
{
   public StudentDto GetExamples()
    {
        return new StudentDto
        {
             StudentName = "John Doe",
             Age = 28
        };
    }
}

Note it is implementing IExamplesProvider<StudentDto> where StudentDto is the main model which I'm sending to the API controller.

And this is how we should apply it for our controller action:

[SwaggerRequestExample(typeof(StudentDto), typeof(StudentDtoDefault))]
[HttpPost]
public ActionResult Post([FromBody] StudentDto student)
{
    ...
}

For more information and example, please visit the GitHub Repository of this project.

Upvotes: 5

Related Questions