Basic Swagger integration gives you a functional API map, but a publicly facing enterprise API (like Stripe or Twilio) requires deeply customized, human-readable documentation. We achieve this by enriching Swashbuckle with custom schemas, examples, and operation filters.
A JSON schema is helpful, but seeing actual "mock data" inside the Swagger UI instantly clarifies what an endpoint expects. We use the Swashbuckle.AspNetCore.Filters package to inject IExamplesProvider.
dotnet add package Swashbuckle.AspNetCore.Filters
public class UserDtoExample : IExamplesProvider<UserDto>
{
public UserDto GetExamples()
{
return new UserDto
{
FirstName = "John",
LastName = "Doe",
Email = "john.doe@enterprise.com",
Age = 35
};
}
}
builder.Services.AddSwaggerExamplesFromAssemblyOf<UserDtoExample>();
builder.Services.AddSwaggerGen(c =>
{
c.ExampleFilters(); // Activates the mock data in the Swagger UI
});
Sometimes you have endpoints (like an internal server health check or an administrative flush-cache trigger) that you absolutely do not want exposed in the public OpenAPI schema.
[ApiController]
[Route("api/admin")]
// This attribute tells Swashbuckle to completely ignore this controller
// when generating the swagger.json file.
[ApiExplorerSettings(IgnoreApi = true)]
public class SecretAdminController : ControllerBase
{
[HttpPost("flush-redis")]
public IActionResult FlushCache() { ... }
}
You do not have to use the default green Swagger UI theme. You can inject custom CSS directly into the Swagger middleware to brand the page with your company's colors and logo.
// In Program.cs
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
// Serve a custom CSS file from the wwwroot folder
c.InjectStylesheet("/swagger-ui/custom-company-theme.css");
// Change the HTML document title
c.DocumentTitle = "Enterprise Corp Developer Portal";
});
Q: "How can we automatically hide endpoints in Swagger from users who do not have the proper Authorization Roles to access them?"
Architect Answer: "Swashbuckle generates the `swagger.json` statically at application startup; it doesn't dynamically change based on who is currently looking at the webpage. However, we can write a custom `IDocumentFilter`. We can inspect the `[Authorize(Roles='Admin')]` attributes on our controllers, and if the endpoint requires Admin, we can tag it with a special metadata badge or physically organize the UI to separate 'Public Endpoints' from 'Admin Endpoints'. To truly hide them dynamically based on the current user's token session, you would need to build a custom API Gateway developer portal (like Azure API Management) rather than relying purely on the static Swagger UI."