LESSON 12 OF 18

12. Professional API Documentation with Swagger/OpenAPI

Learn how to generate OpenAPI documents, configure Swagger UI, document endpoints and DTOs, describe responses, and expose a consistent ProblemDetails contract in ASP.NET Core.

40 dk 100

Introduction

A REST API is not professional merely because it works. Client developers must be able to understand which parameters an endpoint accepts, which request body format it expects, and which response types are returned for successful and failed requests. When this information is missing, clients must inspect implementation details, rely on trial and error, or repeatedly ask the API team for clarification.

OpenAPI is a standard for describing HTTP APIs in a machine-readable format. Swagger is the historical name commonly associated with tools in this ecosystem, especially interactive documentation interfaces. In ASP.NET Core on .NET 10, the Microsoft.AspNetCore.OpenApi package provides built-in support for generating OpenAPI documents. A separate tool such as Swagger UI is still required for a visual, interactive experience.

In this lesson, we will use a small product API that lists products and creates new products. The goal is not only to display a Swagger page, but to turn the API documentation into a contract that client developers can understand and trust.

1. Understanding the roles of OpenAPI and Swagger

ConceptRole
OpenAPIDescribes endpoints, parameters, schemas, responses, and security in a standard format.
OpenAPI documentThe JSON or YAML representation of that contract.
Swagger UIDisplays the OpenAPI document in a browser and enables endpoint testing.
XML commentsMoves descriptions for controllers, actions, DTOs, and parameters from source code into documentation.

This distinction matters. Microsoft.AspNetCore.OpenApi generates the OpenAPI document; it does not automatically provide a visual interface. Swagger UI consumes that document and presents it to developers.

2. Configure a .NET 10 project

First, add the packages required for OpenAPI generation and Swagger UI:

dotnet add package Microsoft.AspNetCore.OpenApi dotnet add package Swashbuckle.AspNetCore.SwaggerUi

Configure the services and middleware in Program.cs:

using Microsoft.AspNetCore.OpenApi; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddOpenApi(); var app = builder.Build(); if (app.Environment.IsDevelopment()) {    app.MapOpenApi();    app.UseSwaggerUI(options =>    {        options.SwaggerEndpoint("/openapi/v1.json", "Catalog API v1");        options.RoutePrefix = "swagger";        options.DocumentTitle = "Catalog API Documentation";        options.DisplayRequestDuration();        options.EnableDeepLinking();    }); } app.UseHttpsRedirection(); app.MapControllers(); app.Run();

When the application runs, the OpenAPI document is typically available at /openapi/v1.json, while Swagger UI is available at /swagger. Restricting the UI to the development environment is a reasonable starting point. If documentation must be available in production, add access control, authentication, and a review of all exposed information.

3. Add descriptions for controllers and endpoints

The first level of documentation is a clear explanation of what each endpoint does. Pay attention to controller names, action descriptions, and operation IDs.

using Microsoft.AspNetCore.Mvc; namespace Catalog.Api.Controllers; /// <summary> /// Handles product catalog operations. /// </summary> [ApiController] [Route("api/products")] [Produces("application/json")] public sealed class ProductsController : ControllerBase {    /// <summary>    /// Returns a filtered list of products.    /// </summary>    /// <param name="page">A one-based page number.</param>    /// <param name="pageSize">The number of records on the page.</param>    /// <returns>A result containing products and pagination information.</returns>    [HttpGet(Name = "GetProducts")]    [ProducesResponseType(typeof(PagedResult<ProductListItemDto>), StatusCodes.Status200OK)]    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]    public ActionResult<PagedResult<ProductListItemDto>> GetProducts(        [FromQuery] int page = 1,        [FromQuery] int pageSize = 20)    {        return Ok();    } }

[ProducesResponseType] tells client developers which data shape is returned for a particular HTTP status code. Documenting only 200 OK produces an incomplete contract. Validation failures, missing resources, unauthorized access, forbidden operations, and unexpected failures should be documented with status codes that match the actual runtime behavior.

4. Document parameters and request bodies

A parameter name alone is not enough. Its unit, default value, permitted range, and required status should be clear. When validation rules are defined on a DTO, the OpenAPI schema should reflect them as much as possible.

public sealed record CreateProductRequest {    /// <summary>The name displayed to users.</summary>    /// <example>Wireless Keyboard</example>    [Required]    [StringLength(120, MinimumLength = 2)]    public required string Name { get; init; }    /// <summary>The product price before taxes.</summary>    /// <example>49.90</example>    [Range(typeof(decimal), "0.01", "999999.99")]    public decimal Price { get; init; }    /// <summary>Indicates whether the product is available.</summary>    /// <example>true</example>    public bool IsActive { get; init; } }

The action should also describe the request and response contract:

/// <summary> /// Creates a new product. /// </summary> /// <remarks> /// Name must contain between 2 and 120 characters. /// Price must be greater than zero. /// </remarks> [HttpPost(Name = "CreateProduct")] [Consumes("application/json")] [ProducesResponseType(typeof(ProductDetailsDto), StatusCodes.Status201Created)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)] public ActionResult<ProductDetailsDto> CreateProduct(CreateProductRequest request) {    return CreatedAtRoute("GetProductById", new { id = 1 }, new ProductDetailsDto()); }

It is also useful to keep an example JSON payload as part of the team’s documentation standard:

{  "name": "Wireless Keyboard",  "price": 49.90,  "isActive": true }

How XML <example> information appears depends on the selected OpenAPI generation and UI approach. If an example does not appear in Swagger UI, add it explicitly with an OpenAPI transformer, custom metadata, or a supported example configuration. Do not assume that writing an XML example always creates a request or response example in every UI.

5. Make DTO schemas understandable

Document DTOs exposed to clients instead of exposing entity classes directly. This prevents database columns, internal fields, and security-sensitive values from leaking into the public API contract.

public sealed record ProductDetailsDto {    /// <summary>The unique identifier of the product.</summary>    /// <example>42</example>    public int Id { get; init; }    /// <summary>The display name of the product.</summary>    /// <example>Wireless Keyboard</example>    public required string Name { get; init; }    /// <summary>The creation time in ISO 8601 format.</summary>    /// <example>2026-10-15T09:30:00Z</example>    public DateTimeOffset CreatedAt { get; init; } }

Property names must match the JSON contract used by clients. If the C# property is CreatedAt and the JSON output is createdAt, verify that the generated Swagger schema also presents the correct name.

6. Document ProblemDetails responses

In the previous lesson, you implemented centralized error handling and ProblemDetails. The next step is to make the same error contract visible in every endpoint’s documentation. A validation error body might look like this:

{  "type": "https://api.example.com/problems/validation-error",  "title": "One or more validation errors occurred.",  "status": 400,  "traceId": "00-abc123",  "errors": {    "name": ["Name is required."]  } }

If the application uses a custom ProblemDetails shape, define it as a DTO:

public sealed record ValidationProblemDetailsDto {    public required string Type { get; init; }    public required string Title { get; init; }    public int Status { get; init; }    public string? TraceId { get; init; }    public IDictionary<string, string[]> Errors { get; init; } = new Dictionary<string, string[]>(); }

Use the actual response type in the endpoint metadata. If the application returns the standard ASP.NET Core ValidationProblemDetails, the documentation should describe that type. A mismatch between the documented response and the real JSON may look acceptable in Swagger UI but will cause problems for generated clients and integrations.

7. Use tags, operation IDs, and versioning

Grouping endpoints by tags makes large APIs easier to navigate. In controller-based applications, the controller name is often used as the tag. Also assign stable and unique operation IDs to operations. Client generation tools may use these values to create method names.

When API versioning is introduced, manage each version’s OpenAPI document deliberately. For example, v1 and v2 can be generated as separate documents with different document names. However, changing the document name alone does not implement route versioning. Routes, controllers, and versioning configuration must work together.

8. Keep documentation secure and maintainable

  • Do not expose Swagger UI anonymously in production: Add authentication and role checks when appropriate.
  • Do not publish sensitive information: Avoid internal service addresses, database details, token examples, and confidential business rules.
  • Describe expected errors: Include both successful responses and relevant error responses for every endpoint.
  • Write useful descriptions: Keep explanations short, action-oriented, and meaningful to client developers.
  • Validate the contract in CI/CD: Generate the OpenAPI document during the build or pipeline and review breaking changes.
  • Do not replace integration tests with Swagger: Try it out is useful for exploration, but it is not a complete automated test strategy.

Common mistakes

  • Showing only URLs: Without parameter and response schemas, the documentation remains incomplete.
  • Returning entities: Database changes can unnecessarily break the public client contract.
  • Documenting every result as 200: Hiding errors causes incorrect client-side flows.
  • Confusing Swagger UI with OpenAPI: The UI may change; the OpenAPI document is the actual contract.
  • Using unrealistic examples: Example JSON must match DTO property names and validation rules.
  • Granting unlimited production test access: Swagger UI can execute real write and delete operations.

Short practice exercise

  1. Add Microsoft.AspNetCore.OpenApi and the Swagger UI package to the existing API.
  2. Expose the OpenAPI document at /openapi/v1.json and Swagger UI at /swagger.
  3. For one list, one create, and one get-by-id endpoint, add descriptions for the operation, parameters, request body, and responses.
  4. Document at least the 400, 404, and 409 results in addition to the successful response.
  5. Send an example request through Swagger UI and compare the displayed schema with the real response body.
  6. Finally, restrict Swagger UI so it runs only in the development environment.

Conclusion

Professional API documentation is much more than a list of URLs. The OpenAPI document provides a machine-readable contract; XML comments and metadata explain endpoint behavior; DTO schemas make request and response shapes visible; and ProblemDetails definitions make error flows predictable.

With built-in OpenAPI generation in .NET 10 and Swagger UI as the interactive consumer, you can create both a standardized document and a developer-friendly interface. The most important rule is to keep documentation aligned with real API behavior. Whenever the API changes, update the document, examples, response types, and security settings as part of the same change.

Sources