Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
t3chb0t Avatar asked Jul 26 '19 08:07

t3chb0t


People also ask

How do I disable try it out in Swagger?

This config can also disable "Try it out" selectively for specific HTTP methods. For example, supportedSubmitMethods: ["get", "head"] keeps "Try it out" only for GET and HEAD, but disables it for POST, PUT, PATCH, DELETE and other methods. Save this answer.


1 Answers

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"),
            };
        }
    }
}
like image 151
Matthias Müller Avatar answered Oct 24 '22 18:10

Matthias Müller