Advertisement
Intermediate ASP.NET Core, API Documentation with Swagger/OpenAPI

How do you customize example values shown in Swagger UI for request and response bodies?

Short answer

Swashbuckle supports IExamplesProvider or the newer Swashbuckle.AspNetCore.Filters package for attaching custom example objects to request/response schemas, or you can use [SwaggerRequestExample]/annotations, giving API consumers realistic sample payloads to reference instead of…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Swashbuckle supports IExamplesProvider or the newer Swashbuckle.AspNetCore.Filters package for attaching custom example objects to request/response schemas, or you can use [SwaggerRequestExample]/annotations, giving API consumers realistic sample payloads to reference instead of Swagger's default auto-generated examples (which are often just default/zero values that don't illustrate realistic usage).
public class ProductExample : IExamplesProvider<ProductDto> {
    public ProductDto GetExamples() => new() { Name = "Wireless Mouse", Price = 29.99m, Category = "Electronics" };
}

builder.Services.AddSwaggerGen(c => c.ExampleFilters());
builder.Services.AddSwaggerExamplesFromAssemblyOf<ProductExample>();
Real-world example
An onboarding developer exploring a new API's Swagger docs immediately understands the expected request shape by seeing a realistic 'Wireless Mouse, $29.99, Electronics' example instead of a default-valued, empty-string placeholder that provides no real guidance.
Likely follow-ups
  • How do default auto-generated examples compare to explicitly authored ones in usefulness?
  • How do you provide different examples for different scenarios of the same endpoint?
Related topics