Setting up a .NET API with Swagger for interactive documentation

An API contract becomes far more useful when developers can read it and send a request without translating the specification by hand. Swagger UI renders an OpenAPI description as an interactive reference: parameters, request bodies, response schemas, authentication controls and examples sit on one page. That shortens the distance between a route that compiles and a route another developer can call correctly, which is valuable for teams spread across Sydney, Melbourne, Brisbane and smaller regional offices. Learn more about Troubleshooting Vsan Decryption And Rekey Operations Post Reboot 5cf3.

For Australian delivery teams, documentation often supports a wider procurement and governance process. An API used by a private insurer, a bank or a government agency may need evidence of secure defaults, predictable error handling and clear handling of personal information. The Australian Privacy Act 1988 and Australian Privacy Principles are relevant when the service processes personal information. Swagger does not satisfy those obligations, but a precise contract makes the intended controls, data fields and failure modes easier to review. Learn more about Using Angulars Eventemitter To Share Data Between Child And Parent Components.

Scaffold the API and add Swagger

Start with a supported .NET LTS and a controller-based template. Controllers make XML comments, response attributes and conventional routing easy to demonstrate, while minimal APIs can use the same Swagger tooling. Create the solution, restore dependencies and add Swashbuckle with the .NET CLI:

dotnet new webapi -n OrdersApi --use-controllers
cd OrdersApi
dotnet add package Swashbuckle.AspNetCore
dotnet restore

Register endpoint discovery and Swagger generation before the application builds its request pipeline. In a minimal Program.cs, the essential shape is:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapControllers();
app.Run();

Run the project with dotnet run and use the HTTPS URL printed by the launch profile. The /swagger route opens the interactive interface, while /swagger/v1/swagger.json exposes the machine-readable OpenAPI document. If the page returns 404, check that AddSwaggerGen and both Swagger middleware calls remain registered. Trust the local HTTPS development certificate when prompted, or use the HTTP profile while evaluating the setup. Keep the middleware behind the development-environment check shown here, then decide separately whether a protected staging copy should be available. Current .NET templates may offer built-in OpenAPI generation, but Swashbuckle remains a practical choice when Swagger UI, XML comments and reusable examples are priorities.

Make the OpenAPI contract useful

Return dedicated response models rather than database entities. A small record keeps the public shape obvious and prevents accidental exposure of internal fields. Choose names once, keep them stable, and document whether values can be null.

public sealed record CustomerSummary(
    string Id,
    string DisplayName,
    string OrganisationName);

XML comments supply summaries, parameter descriptions and response meanings, while attributes let Swagger infer status codes and schemas. Enable the XML documentation file in the project settings, then include it during Swagger registration. This keeps the endpoint behaviour and its published description close together:

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
/// <summary>Returns a customer by its stable identifier.</summary>
/// <param name="id">The customer identifier, such as cus_42.</param>
/// <response code="200">The matching customer.</response>
/// <response code="404">No customer has the supplied identifier.</response>
[HttpGet("{id}")]
[Produces("application/json")]
[ProducesResponseType<CustomerSummary>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<CustomerSummary> GetById(string id)
{
    if (id != "cus_42")
        return NotFound();

    return Ok(new CustomerSummary(
        "cus_42",
        "Alex Morgan",
        "Wattle Consulting Pty Ltd"));
}

Swagger can infer a schema but not always a useful example body. Add Swashbuckle.AspNetCore.Filters and implement IOExampleFilter when realistic request or response values make the trial flow easier to understand. The same discipline applies to errors: document validation failures with a consistent ProblemDetails shape, identify which fields caused a 400 response, and state when a 204 response contains no body. Avoid exposing stack traces or internal database details in the public contract.

Operational failures deserve the same precision as successful calls. The [VSAN rekey operations] guide illustrates why a runbook should name prerequisites, verification steps, recovery actions and evidence after a risky change. Apply that discipline to each API operation: say which validation code comes back, whether a retry is safe, and how a caller distinguishes “not found” from “not authorised”. Naming and prose can use Australian English, including “organisation” and “customise”, while identifiers remain consistent with the domain.

Secure and publish the documentation

Give the document a stable identity and useful grouping. Configure an OpenAPI title, version, description and tags so the UI reads like a product rather than a route dump. If a service has several audiences, group operations by business capability, such as Customers, Orders and Billing. The generated JSON should also have a predictable route because CI jobs, client generators and support teams can then reference it directly.

using System.Reflection;
using Microsoft.OpenApi.Models;

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Orders API",
        Description = "Customer order operations",
        Version = "v1"
    });

    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(
        Path.Combine(AppContext.BaseDirectory, xmlFile));
});

app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Orders API v1");
    options.DocumentTitle = "Orders API documentation";
    options.DisplayRequestDuration();
});

Authentication is part of the contract, not an optional decoration. For JWT-protected endpoints, declare the bearer scheme so Swagger UI displays an Authorize control where a developer can provide a short-lived token. OAuth2 services should also list their required scopes because the UI can initiate the configured sign-in flow. The scheme advertises how to authenticate, but it does not enforce access, so protect the corresponding endpoints with [Authorize] and suitable authorization policies.

options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
    Name = "Authorization",
    Type = SecuritySchemeType.Http,
    Scheme = "bearer",
    BearerFormat = "JWT",
    In = ParameterLocation.Header
});

options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
            }
        },
        Array.Empty<string>()
    }
});

Publishing the UI does not mean exposing sensitive implementation detail without a gate. Keep it on HTTPS, require authentication where the API is internal, and restrict access to an internal developer portal or an authenticated staging environment. In Australian cloud deployments, select a Sydney or Melbourne region when contractual or latency requirements call for it, and record that decision without assuming all providers use identical region names. A Brisbane team might reckon the endpoint is finished when the build is green; the Swagger document should make its expected status and payload just as verifiable.

Exercise every endpoint from Swagger UI

Start the API, open /swagger, and use Try it out on a read-only endpoint before testing a write. Expand the operation, inspect each parameter and request-body schema, then select Execute. Compare the status code, content type and response body with the published contract. Test an invalid parameter, a missing token and an inaccessible record as well as the successful path; each should produce the documented result without an HTML error page or an undeclared response shape. If a team says the service must be ready by arvo, “it built successfully” is not enough evidence, while an executable request is.

A useful smoke test is a request for a known customer. With a bearer token, the request should return the customer identifier, display name and organisation name in the documented shape. Try an unknown identifier as well, and confirm that the API returns the documented not-found response instead of an undeclared empty body.

GET /api/customers/cus_42
Authorization: Bearer <access-token>
Accept: application/json

The page is also a handoff artefact for frontend teams. The article on [Angular component data sharing] shows the value of a clearly published event contract between parent and child components. An HTTP API needs the same discipline: stable field names, predictable status codes and examples that expose nullability and date formats. That consistency lets a consumer build a typed client without reverse-engineering responses from screenshots or tribal knowledge.

Ship a repeatable documentation workflow

Treat the OpenAPI document as a versioned product artefact. Generate it during the build, validate it with an OpenAPI parser, and compare changes so a renamed field or removed status code cannot slip into production unnoticed. A lightweight release checklist can cover the essentials:

Australian enterprise and public-sector buyers commonly ask for security evidence, service-level terms, support arrangements and clear ownership before a platform is approved. The Australian Signals Directorate’s Australian Cyber Security Centre publishes the Essential Eight, and related controls may inform those assessments, although Swagger itself is not a compliance product. Support hours should match the customer base, including Australian Eastern Time and Australian Central Time where relevant, while hosted options should cover Australian data-residency requirements where they apply. A short note beside the UI can explain the environment, owner and support channel without cluttering every operation.

Open a terminal, create the project, add Swagger and make one endpoint executable from Swagger UI. That first verified response gives the team a shared contract they can test, publish and extend.