Introduction
An API should do more than return correct results. Frontend developers, mobile teams, integration services, and QA engineers need to understand which URLs an API exposes, which HTTP methods it supports, which request models it expects, and which responses it can return. When this information is incomplete or scattered across conversations and source files, using the API becomes guesswork and creates unnecessary communication costs.
In this lesson, we will bring the documentation of our Clean Architecture ASP.NET Core Web API to a professional level by configuring Swagger and OpenAPI. OpenAPI is a language-independent standard for describing HTTP APIs in a machine-readable format. Swagger is the name commonly associated with the tooling ecosystem that generates, displays, and interacts with OpenAPI documents. In simple terms, OpenAPI defines the document format, while Swagger UI provides a browser-based interface for exploring and testing that document.
In the previous lesson, we implemented centralized error handling and Problem Details. In this lesson, we will make those responses visible in the OpenAPI document. API consumers will therefore be able to inspect not only successful responses, but also validation errors, missing resources, and expected error formats before writing client code.
The Difference Between OpenAPI and Swagger
The OpenAPI Specification standardizes the description of endpoints, parameters, request bodies, response status codes, security definitions, and data schemas. The document can be generated in JSON or YAML format.
Swagger was historically used as the name of the specification and is now commonly used for a collection of tools around OpenAPI. In ASP.NET Core applications, the widely used Swashbuckle.AspNetCore package discovers controllers and actions, generates an OpenAPI document, and displays it through Swagger UI.
- OpenAPI: The standard, machine-readable definition of an API contract.
- Swagger document: The generated OpenAPI JSON or YAML document.
- Swagger UI: A browser interface that lists endpoints and allows interactive testing.
- API Explorer: ASP.NET Core infrastructure that discovers endpoint metadata.
Adding the Required Package
To use Swagger UI in the Presentation or API project, add the Swashbuckle package. Run the following command from the project directory:
dotnet add package Swashbuckle.AspNetCore.NET 10 also includes built-in OpenAPI support in ASP.NET Core. The built-in support focuses on generating OpenAPI documents; an interactive interface such as Swagger UI can be added separately. In this lesson, we will use the Swashbuckle approach because it fits our existing controller-based API and is widely used in professional teams.
Configuring Program.cs
First, register API Explorer and the Swagger generator in the service collection:
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Catalog API",
Version = "v1",
Description = "Catalog API built with Clean Architecture",
Contact = new OpenApiContact
{
Name = "API Support",
Email = "support@example.com"
}
});
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Catalog API v1");
options.RoutePrefix = "swagger";
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();AddEndpointsApiExplorer helps ASP.NET Core discover controller endpoints. AddSwaggerGen registers the OpenAPI document generator. UseSwagger exposes the generated JSON document, while UseSwaggerUI displays it through an interactive browser interface.
In this example, Swagger is enabled only in the Development environment. Publishing API documentation publicly in production should be evaluated carefully because the document may reveal endpoint names, request models, and implementation details. If production access is required, use authentication, a separate administration area, or a protected reverse proxy.
Adding Controller and Endpoint Descriptions
Automatically generated documentation contains basic endpoint information, but a professional API should include meaningful descriptions. XML comments, response attributes, and clear naming can be used at both controller and action levels.
using Microsoft.AspNetCore.Mvc;
namespace Catalog.Api.Controllers;
/// <summary>
/// Provides endpoints for catalog product operations.
/// </summary>
[ApiController]
[Route("api/products")]
[Produces("application/json")]
public sealed class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
/// <summary>
/// Gets a product by its identifier.
/// </summary>
/// <param name="id">The product identifier.</param>
/// <returns>The requested product response.</returns>
/// <response code="200">The product was found.</response>
/// <response code="404">The product was not found.</response>
[HttpGet("{id:int}")]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProductResponse>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await _productService.GetByIdAsync(id, cancellationToken);
if (product is null)
{
return NotFound();
}
return Ok(product);
}
}The XML comments provide human-readable descriptions, while ProducesResponseType attributes add response status and model metadata to the OpenAPI document. Swagger UI can then show that a 200 response returns ProductResponse and a 404 response returns ProblemDetails.
Enabling XML Documentation Comments
To display XML comments in the Swagger document, enable XML documentation generation in the API project file:
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>Then configure Swagger to load the generated XML file in Program.cs:
using System.Reflection;
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Catalog API",
Version = "v1"
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
});If the XML file name and assembly name differ, Swagger may not find the file. Before running the application, verify that the XML documentation file is actually generated in the appropriate bin directory.
Documenting Request and Response Models
DTOs are an important part of the API contract. We should continue using request and response DTOs from the Application layer instead of exposing Domain entities directly. Swagger should document the public contract, not expose database implementation details.
public sealed record CreateProductRequest(
string Name,
decimal Price,
int CategoryId);
public sealed record ProductResponse(
int Id,
string Name,
decimal Price,
int CategoryId,
DateTime CreatedAtUtc);Response metadata for a create endpoint can be defined as follows:
[HttpPost]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
public async Task<ActionResult<ProductResponse>> Create(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var result = await _productService.CreateAsync(request, cancellationToken);
return CreatedAtAction(
nameof(GetById),
new { id = result.Id },
result);
}Here, 201 Created represents a successful creation, 400 Bad Request represents a validation failure, and 409 Conflict represents a business conflict such as attempting to create a product with a duplicate name. Documenting all important results helps API consumers implement correct success and error handling.
FluentValidation and ValidationProblemDetails
In the previous lesson, we defined request validation rules with FluentValidation. When an invalid request is submitted, controller-based ASP.NET Core APIs commonly return a ValidationProblemDetails response. This response contains field-specific validation messages.
public sealed class CreateProductRequestValidator
: AbstractValidator<CreateProductRequest>
{
public CreateProductRequestValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(150);
RuleFor(x => x.Price)
.GreaterThan(0);
RuleFor(x => x.CategoryId)
.GreaterThan(0);
}
}Meaningful DTO property names help Swagger UI display understandable request body fields. Examples and descriptions may also be added when necessary. However, validation rules must be enforced by validators at runtime; documentation does not replace validation. Swagger only describes the expected contract.
Documenting Problem Details Responses
Our centralized error handling gives the API a consistent error format. Declaring error responses in the Swagger document allows client developers to understand the expected response body.
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]A ValidationProblemDetails response commonly includes type, title, status, traceId, and an errors dictionary containing field-level messages. If our custom error middleware uses a different response model, that model should be represented by a DTO and added to the OpenAPI metadata. The model displayed in the documentation must match the actual response returned by the application.
Adding Authentication Information to Swagger UI
In later lessons, we will use JWT authentication and authorization. To test protected endpoints through Swagger UI, define a security scheme:
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter a JWT token using the Bearer {token} format."
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});This configuration makes the Authorize button available in Swagger UI. After a valid token is entered, Swagger UI adds the token to the Authorization header of requests. Tokens should never be shared, and production data should not be used carelessly during interactive testing.
Common Mistakes
- Thinking Swagger is a security layer: Swagger is a documentation and testing tool. It does not enforce authorization rules.
- Documenting only successful responses: Showing only
200responses prevents consumers from implementing reliable error handling. - Exposing Domain entities directly: This can leak persistence details and make the public API contract unnecessarily fragile.
- Ignoring the XML file path: Controller descriptions will not appear if XML documentation generation is disabled or the file cannot be found.
- Allowing documentation to drift: If the document declares
ProductResponsebut the action returns a different shape, client trust decreases. - Leaving public Swagger enabled in production: Endpoint lists, model details, and security information should not be exposed without a deliberate access policy.
Practice Exercise: Document the Product Endpoint
- Add the
Swashbuckle.AspNetCorepackage to the API project. - Configure
AddEndpointsApiExplorer,AddSwaggerGen,UseSwagger, andUseSwaggerUI. - Add XML summaries and parameter descriptions to
ProductsController. - Document the
200,404, and possible500responses forGET /api/products/{id}. - Add response models for
201,400, and409toPOST /api/products. - Run the application and test both valid and invalid requests from Swagger UI.
- Open the generated OpenAPI JSON and verify that endpoint descriptions, schemas, and status codes are present.
Conclusion
In this lesson, we transformed the API from a collection of working endpoints into a discoverable, testable, and developer-friendly contract. OpenAPI provides a machine-readable definition of the API, while Swagger UI makes that definition visual and interactive.
We documented endpoint descriptions, DTO schemas, response status codes, FluentValidation results, and the Problem Details error format. We also saw that Swagger is not a security mechanism and should be configured carefully in production. High-quality API documentation is not merely a collection of explanatory sentences; it is a complete, current contract that accurately represents the application’s real behavior.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/overview?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/include-metadata?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-7.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling-api?view=aspnetcore-10.0