'Specify example requests for swagger's "Try it out"

Is there a way to specify example requests for swagger? Maybe even multiple ones?

The Try it out button shows only generic values like:

{
    "firstName": "string",
    "lastName": "string"
}

for

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

It becomes very difficult to use with large objects when you have to edit all the values first. I know I could use Postman, and I do too, but being able to create multiple good looking and useful examples with swagger would be very nice.



Solution 1:[1]

In .Net5 you can add a SchemaFilter to Swagger in the Startup.cs

public override void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SchemaFilter<ExampleSchemaFilter>();
    });
}

In the ExampleSchemaFilter.cs you simply define an OpenApiObject for your specific class:

using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class ExampleSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == typeof(User))
        {
            schema.Example = new OpenApiObject()
            {
                ["firstName"] = new OpenApiString("John"),
                ["lastName"] = new OpenApiString("Doe"),
            };
        }
    }
}

Solution 2:[2]

With ASP.NET Core 3.1, Swagger OAS 3 and Swashbuckle.AspNetCore 5.4.1, the following model class + XML comments works for me:-

    /// <summary>
    /// A user.
    /// </summary>
    public class User
    {
        /// <summary>
        /// The user's first name.
        /// </summary>
        /// <example>Jane</example>
        public string FirstName { get; set; }

        /// <summary>
        /// The user's last name.
        /// </summary>
        /// <example>Austin</example>
        public string LastName { get; set; }
    }

Now when I click "Try it Out" (for a POST operation that takes a User model in the message body), I get the defaults:-

{
    "firstName": "Jane",
    "lastName": "Austin"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthias Müller
Solution 2 Bellarmine Head