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.
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.
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"),
};
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With