Search code examples
c#asp.net-core-webapiswagger-uiswashbuckle.aspnetcore

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

  • 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"),
                };
            }
        }
    }