Lesson 7 of 8
OpenAPI / Swagger Documentation
Swagger UI with OpenAPI 3.0 provides interactive API documentation that lets developers test endpoints without Postman. XML documentation comments generate descriptions automatically. NSwag or Swashbuckle can generate client SDK code from the OpenAPI spec.
Production Swagger Configuration
// dotnet add package Swashbuckle.AspNetCore
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1",
Description = "Production-grade ASP.NET Core REST API",
Contact = new OpenApiContact { Name = "API Team", Email = "api@myapp.com" },
License = new OpenApiLicense { Name = "MIT" }
});
// ━━ JWT auth in Swagger UI ━━
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter your JWT token. Example: 'eyJ...'"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
Array.Empty<string>()
}
});
// ━━ Include XML doc comments ━━
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
// ━━ Enable example generation ━━
options.EnableAnnotations();
});
// In .csproj - generate XML docs:
// <PropertyGroup>
// <GenerateDocumentationFile>true</GenerateDocumentationFile>
// <NoWarn>$(NoWarn);1591</NoWarn> <!-- suppress warnings for undocumented members -->
// </PropertyGroup>
// ━━ Document an endpoint with XML comments ━━
/// <summary>Creates a new product</summary>
/// <param name="request">Product creation data</param>
/// <param name="ct">Cancellation token</param>
/// <returns>The created product with its assigned ID</returns>
/// <remarks>
/// Sample request:
/// <code>
/// POST /api/products
/// { "name": "Widget", "price": 9.99, "currency": "USD" }
/// </code>
/// </remarks>
/// <response code="201">Product created successfully</response>
/// <response code="400">Invalid request data</response>
/// <response code="409">Product name already exists</response>
[HttpPost]
[ProducesResponseType<ProductDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Create([FromBody] CreateProductRequest request, CancellationToken ct) => Ok();
record CreateProductRequest(string Name, decimal Price, string Currency);Tip
Tip
Practice OpenAPI Swagger Documentation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of OpenAPI Swagger Documentation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with OpenAPI Swagger Documentation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?