ASP.NET Core  

Smart API Documentation: Auto-Generating Swagger Descriptions using AI in ASP.NET Core

1. Introduction

In every modern development project, API documentation plays a crucial role in helping developers understand and integrate backend services efficiently. However, maintaining accurate, up-to-date API documentation is often one of the most neglected tasks in software projects.

Developers frequently make changes to API endpoints, models, or parameters, but forget to update the Swagger descriptions or XML comments — resulting in outdated and confusing documentation.

To solve this problem, we can now use Artificial Intelligence (AI) to automatically generate or update Swagger descriptions based on the actual code, business context, and naming conventions.

This article explains how to integrate AI-based documentation generation into your ASP.NET Core Web API project using OpenAI or Azure OpenAI along with Swagger (Swashbuckle). You’ll learn how to automatically generate endpoint summaries, parameter details, and model descriptions — all in a clean and developer-friendly way.

2. Why Automate API Documentation?

Manually maintaining Swagger documentation is time-consuming and error-prone. The main challenges include:

  • Developers forget to update Swagger descriptions after changing code.

  • Descriptions are inconsistent across multiple APIs.

  • No standard tone or style in documentation.

  • Lack of clarity for external developers integrating the API.

AI-powered documentation addresses these problems by:

  • Generating contextual and natural language explanations.

  • Keeping descriptions synchronized with the actual source code.

  • Saving time for developers.

  • Providing documentation in a consistent, easy-to-read tone.

3. Workflow Overview

Let’s visualize how AI can automatically enhance Swagger documentation in an ASP.NET Core API project.

Flowchart: AI-Generated Swagger Workflow

Developer updates API code
        |
        v
Swagger Middleware scans all Controllers and Actions
        |
        v
AI Engine analyzes code and generates summaries (via OpenAI API)
        |
        v
Swagger JSON enriched with AI-generated descriptions
        |
        v
Updated Swagger UI with smart documentation

This flow ensures that every time you build or deploy your API, AI reviews your code and updates the Swagger documentation automatically.

4. Project Setup

Step 1: Create a new ASP.NET Core Web API Project

dotnet new webapi -n SmartApiDocs
cd SmartApiDocs

Step 2: Add Swagger Support

Install the Swashbuckle.AspNetCore package:

dotnet add package Swashbuckle.AspNetCore

Step 3: Add OpenAI SDK (or Azure OpenAI SDK)

For example, using the OpenAI .NET client:

dotnet add package OpenAI

Or, if you’re using Azure OpenAI:

dotnet add package Azure.AI.OpenAI

5. Configuring Swagger in ASP.NET Core

In Program.cs:

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.UseAuthorization();
app.MapControllers();
app.Run();

This sets up basic Swagger documentation. When you run the project, you can access Swagger UI at /swagger.

6. The Challenge: Missing Descriptions

A standard Swagger file generated by Swashbuckle may look like this:

{"paths": {
    "/api/customer/{id}": {
      "get": {
        "summary": "",
        "description": "",
        "parameters": [
          { "name": "id", "description": "" }
        ]
      }
    }}}

As you can see, all the important descriptions are missing. This is where we’ll use AI to fill the gaps.

7. Integrating AI for Auto-Generated Descriptions

Step 1: Create an AI Helper Service

Create a new class AIService.cs:

using OpenAI_API;

public class AIService
{
    private readonly OpenAIAPI _api;

    public AIService(string apiKey)
    {
        _api = new OpenAIAPI(apiKey);
    }

    public async Task<string> GenerateDescriptionAsync(string endpointName, string parameters)
    {
        var prompt = $"Write a short API documentation summary for an endpoint named '{endpointName}' with parameters {parameters}. " +
                     "Explain in a professional tone suitable for Swagger documentation.";

        var response = await _api.Completions.GetCompletion(prompt);
        return response.ToString();
    }
}

This service uses OpenAI to generate contextual documentation text based on endpoint names and parameters.

Step 2: Modify Swagger Generation

We’ll hook into Swagger generation to enrich endpoints automatically.

Create a new file AIDescriptionDocumentFilter.cs:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class AIDescriptionDocumentFilter : IDocumentFilter
{
    private readonly AIService _aiService;

    public AIDescriptionDocumentFilter(AIService aiService)
    {
        _aiService = aiService;
    }

    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var path in swaggerDoc.Paths)
        {
            foreach (var operation in path.Value.Operations)
            {
                if (string.IsNullOrEmpty(operation.Value.Description))
                {
                    var endpointName = path.Key;
                    var parameters = string.Join(", ", operation.Value.Parameters.Select(p => p.Name));

                    var description = _aiService.GenerateDescriptionAsync(endpointName, parameters).Result;
                    operation.Value.Description = description;
                    operation.Value.Summary = description.Length > 100 ? description.Substring(0, 100) + "..." : description;
                }
            }
        }
    }
}

This custom document filter dynamically updates the Swagger JSON before it’s rendered on the UI.

Step 3: Register the Filter and AI Service

Update Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.DocumentFilter<AIDescriptionDocumentFilter>();
});

builder.Services.AddSingleton(new AIService(builder.Configuration["OpenAI:ApiKey"]));

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

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

Now, when Swagger runs, it will call the AI service to populate missing descriptions automatically.

8. Example in Action

Consider this simple controller:

[ApiController]
[Route("api/[controller]")]
public class CustomerController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetCustomer(int id)
    {
        return Ok(new { Id = id, Name = "John Doe", Status = "Active" });
    }

    [HttpPost]
    public IActionResult AddCustomer(Customer customer)
    {
        return CreatedAtAction(nameof(GetCustomer), new { id = 1 }, customer);
    }
}

Without any XML comments, Swagger would display blank summaries.

With the AI-powered integration, you’ll get:

"summary": "Retrieves customer information by ID and returns name and status.","description": "This endpoint retrieves detailed customer information using the provided customer ID. Useful for profile or billing systems."

and for the POST endpoint:

"summary": "Adds a new customer record.","description": "This API allows creating a new customer record in the system. It requires customer name, contact details, and status."

Now your Swagger UI automatically stays meaningful and developer-friendly — without manual editing.

9. Storing AI-Generated Descriptions

You can persist AI-generated Swagger text in:

  • A local JSON file (swagger-descriptions.json).

  • A database (for version control and reuse).

  • A cache layer (Redis or MemoryCache) to avoid repeated API calls.

Example

File.WriteAllText("swagger-descriptions.json", JsonSerializer.Serialize(swaggerDoc));

This ensures AI generation only happens for new or modified endpoints.

10. Security and Cost Optimization

To prevent unnecessary API usage and protect your keys:

  • Cache all generated descriptions.

  • Use environment-based AI keys (different for dev/test/prod).

  • Add rate limiting for AI requests.

  • Avoid sending sensitive code or parameters to AI APIs.

11. Enhancements

You can take this idea further:

  1. Generate Model Descriptions — Scan your DTOs and have AI generate schema explanations.

  2. Multi-Language Docs — Translate Swagger descriptions automatically using AI translation APIs.

  3. Consistency Check — Use AI to validate tone and grammar of manually written descriptions.

  4. Version-aware Docs — Track changes between API versions and highlight differences automatically.

12. Deployment and CI/CD Integration

Integrate this process in your build or release pipeline:

  1. On each build, a script runs Swagger generation.

  2. The Swagger JSON is processed by the AI service.

  3. Updated documentation is published to your API portal.

Example Jenkins stage

dotnet build
dotnet test
dotnet swagger tofile --output swagger.json bin/Debug/net8.0/SmartApiDocs.dll v1
dotnet run --update-swagger-ai

13. Benefits of AI-Driven Swagger Documentation

AspectTraditional ApproachAI-Generated Approach
Time to DocumentHighVery Low
ConsistencyVaries by developerUniform tone and structure
MaintenanceManual updatesAutomated regeneration
ClaritySometimes vagueContextual and natural
Multi-Language SupportManualAutomated

14. Best Practices

  • Always review AI-generated content before publishing.

  • Combine AI-generated text with developer review for accuracy.

  • Implement logging to see which endpoints were auto-documented.

  • Use fine-tuned prompts for specific project tone or brand guidelines.

  • Include change tracking to compare old and new descriptions.

Conclusion

AI-powered documentation is transforming how teams maintain and share their APIs. By integrating OpenAI or Azure OpenAI into your Swagger generation pipeline, you can ensure your ASP.NET Core APIs always have high-quality, human-readable, and up-to-date documentation.

This approach saves hours of manual writing effort while keeping developers, testers, and clients aligned with the latest API changes.

With this method, documentation becomes a living part of your API, not an afterthought.