RA.Utilities.OpenApi 10.3.1

Prefix Reserved
dotnet add package RA.Utilities.OpenApi --version 10.3.1
                    
NuGet\Install-Package RA.Utilities.OpenApi -Version 10.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RA.Utilities.OpenApi" Version="10.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RA.Utilities.OpenApi" Version="10.3.1" />
                    
Directory.Packages.props
<PackageReference Include="RA.Utilities.OpenApi" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RA.Utilities.OpenApi --version 10.3.1
                    
#r "nuget: RA.Utilities.OpenApi, 10.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RA.Utilities.OpenApi@10.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RA.Utilities.OpenApi&version=10.3.1
                    
Install as a Cake Addin
#tool nuget:?package=RA.Utilities.OpenApi&version=10.3.1
                    
Install as a Cake Tool

RA.Utilities.OpenApi

NuGet version Codecov NuGet Downloads Documentation GitHub license

A utility library to enhance and customize OpenAPI (Swagger) documentation in ASP.NET Core applications.

This package provides a collection of IOpenApiDocumentTransformer implementations to automate common modifications to your generated OpenAPI specification. Instead of manually annotating every endpoint with attributes for common headers or security schemes, you can apply these transformations globally.

The primary goals are to:

  • Reduce Boilerplate: Automatically add common parameters (like correlation IDs) to all API operations.
  • Enforce Consistency: Ensure that all endpoints consistently document required headers and responses.
  • Simplify Configuration: Keep your endpoint definitions clean by centralizing OpenAPI modifications.

📚 Table of Contents

Getting Started

Install the package via the .NET CLI:

dotnet add package RA.Utilities.OpenApi

Or through the NuGet Package Manager in Visual Studio.


Document Transformers

This package includes a set of document transformers that can be registered with a single extension method, AddDefaultsDocumentTransformer().

DocumentInfoTransformer

This transformer populates the top-level information of your OpenAPI document (like title, version, description, and contact info) directly from your appsettings.json configuration.

What it does:

  1. Reads from Configuration: It uses OpenApiInfoSettings to bind to a configuration section (e.g., OpenApiInfoSettings).
  2. Populates OpenApiInfo: It sets the Title, Version, Description, Summary, TermsOfService, Contact, and License fields in the generated document (the Summary field is populated since v10.1.1).
  3. Simplifies Customization: Allows you to update your API's documentation details without changing any code.

BearerSecurityDocumentTransformer

This transformer automatically adds a "Bearer" security scheme to your OpenAPI document if it detects that JWT Bearer authentication is registered in your application. This enables the "Authorize" button in the Swagger UI, allowing users to test protected endpoints.

What it does:

  1. Detects JWT Authentication: It checks if an authentication scheme named Bearer or BearerToken is present.
  2. Adds Security Scheme: If detected, it adds the standard JWT Bearer security definition to the document's components.
  3. Reduces Boilerplate: Eliminates the need to manually configure AddSecurityDefinition and AddSecurityRequirement in SwaggerGenOptions for this common scenario.

HeadersParameterTransformer

This document transformer automatically adds common correlation and tracing headers to every operation in your OpenAPI document. This is useful for microservices and distributed systems where tracking requests is essential.

What it does:

  1. Adds Request Headers: It adds headers like x-request-id as parameters to all API requests. This documents the need for clients to provide a unique identifier for each call.
  2. Adds Response Headers: It adds headers like x-request-id and trace-id to all possible responses for every operation. This informs clients that they can expect these headers back for logging and debugging.

Both the request and response headers are configurable via HeadersParameterSettings.

HealthChecksDocumentTransformer

This document transformer adds your service's health check endpoints to the OpenAPI document. Endpoints mapped with MapHealthChecks carry no API metadata, so the OpenAPI generator never includes them; this transformer documents them explicitly.

What it does:

  1. Documents GET /health: The readiness endpoint that returns the aggregate health status of the service together with the result of each registered health check, as application/json (200/503 responses described with the HealthCheckReport schema).
  2. Documents GET /alive: The liveness endpoint that returns the service state as plain text (Healthy, Degraded, or Unhealthy), based on the health checks tagged with live (200/503 responses as text/plain).
  3. Adds component schemas: HealthCheckReport (aggregate status, totalDuration, and per-check entries) and HealthCheckEntry (data, description, duration, exception, status, tags).
  4. Adds the Health tag and keeps the operations anonymous — the transformer runs after the Bearer security transformer, so no security scheme is applied and the endpoints stay reachable without authentication.

It is registered automatically by AddDefaultsDocumentTransformer().

⚠️ Known issue (v10.1.0, still present in v10.3.1): The standalone AddHealthChecksDocumentTransformer(IDictionary<string, string> tags) extension method currently registers HeadersParameterTransformer instead of HealthChecksDocumentTransformer, and the tags argument is ignored. Use AddDefaultsDocumentTransformer() until this is corrected.


Operation Transformers

DefaultResponsesOperationTransformer

This operation transformer automatically adds standardized OpenAPI responses for common HTTP status codes for 500. It uses the response models from RA.Utilities.Api.Response (namespace RA.Utilities.Api.Response) to generate the schema for these error responses.

This transformer is an IOpenApiOperationTransformer, meaning it applies to each API operation individually. It is a more targeted alternative to the ResponsesDocumentTransformer.

What it does:

  1. Standardizes Error Responses: Ensures that your OpenAPI documentation accurately reflects the structured error responses (ErrorResponse) that your API produces.
  2. Reduces Annotations: Eliminates the need to manually add [ProducesResponseType] attributes for these common errors on every single endpoint.
  3. Operation-Level Granularity: As an IOpenApiOperationTransformer, it integrates seamlessly with ASP.NET Core's native operation-level processing pipeline.

Polymorphism (as a Document Transformer)

PolymorphismDocumentTransformer

This document transformer enhances the OpenAPI documentation for APIs that use polymorphic types (i.e., base classes with multiple derived classes). It correctly represents the inheritance structure in the generated schema using the oneOf and discriminator keywords, making it understandable for clients and code generation tools.

Unlike a Swashbuckle ISchemaFilter, this is an IOpenApiDocumentTransformer that works with ASP.NET Core's native OpenAPI generation (Microsoft.AspNetCore.OpenApi).

What it does:

  1. Finds the Base Schema: It locates the schema for a specified base type in the OpenAPI document.
  2. Generates Derived Schemas: It ensures that schemas for all specified derived types are present in the document, creating them if necessary.
  3. Adds oneOf and discriminator: It modifies the base schema to use the oneOf keyword, listing all derived types, and adds a discriminator object to tell clients how to determine the correct type based on a property (e.g., "type").
  4. Enables Code Generation: Fixes issues with client-side code generators like NSwag or AutoRest where polymorphic types would otherwise be ignored or misinterpreted.

To apply this transformer, use the AddPolymorphismDocumentTransformer<T> extension method:

// Program.cs
builder.Services.AddOpenApi(options =>
{
    options.AddPolymorphismDocumentTransformer<Animal>(new Dictionary<string, Type>
    {
        { "Cat", typeof(Cat) },
        { "Dog", typeof(Dog) },
    });
});

Schema Transformers

FluentValidationSchemaTransformer

This transformer enriches your OpenAPI schema by applying constraints from your FluentValidation validators. It inspects registered IValidator<T> implementations and adds corresponding constraints (required, length, pattern, range) to the generated schema properties.

Supported Rules:

  • NotNull / NotEmpty → marks property as required
  • Length / MinimumLength / MaximumLength → sets minLength / maxLength
  • Matches → sets pattern
  • GreaterThan / LessThan → sets minimum / maximum with exclusive flags
  • InclusiveBetween / ExclusiveBetween → sets minimum / maximum range
  • EmailAddress → sets format to email
  • CreditCard → sets format to credit-card
builder.Services.AddOpenApi(options =>
{
    options.AddFluentValidationRules();
});

ValueObjectSchemaTransformer

Documents the constraints enforced by the value objects from RA.Utilities.Core.ValueObjects directly in the generated schema. The OpenAPI generator cannot see the validation performed by a value object's constructor, so without this transformer Email, Currency, SSN, and IBAN appear as property-less objects.

Value object Documented schema
Email string, format: email, pattern, minLength: 1, maxLength: 254
Currency string, pattern, minLength: 3, maxLength: 3
SSN string, pattern, minLength: 10, maxLength: 10
IBAN string, format: iban, pattern, minLength: 13, maxLength: 34
Money object description and example

Each schema also receives a description and an example value. The transformer is idempotent and is registered automatically by AddDefaultsDocumentTransformer(). When registering transformers individually, add it explicitly:

builder.Services.AddOpenApi(options =>
{
    options.AddValueObjectSchemaTransformer();
});

EnumXmlSchemaTransformer

Enhances enum definitions in the OpenAPI schema by reading XML documentation comments and appending a markdown table with value descriptions. Requires your project to generate an XML documentation file.

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

builder.Services.AddOpenApi(options =>
{
    options.AddEnumXmlDescriptionTransformer(xmlPath);
});

TagOperationTransformer

Allows you to add or update descriptions for OpenAPI tags, which is useful for documenting controller groups without cluttering the code with attributes.

builder.Services.AddOpenApi(options =>
{
    options.AddTagOperationTransformer(new Dictionary<string, string>
    {
        { "Products", "Operations related to product management." },
        { "Orders", "Operations for processing customer orders." }
    });
});

GroupTagsDocumentTransformer

Writes group-level documentation declared with WithGroupSummary() / WithGroupDescription() into the OpenAPI tags of a route group. Endpoint-level WithSummary() / WithDescription() metadata is left untouched, so the group text and the endpoint text never fight over the same field.

using RA.Utilities.OpenApi.Extensions;

var orders = app.MapGroup("/orders")
    .WithTags("Orders")
    .WithGroupSummary("Order management")
    .WithGroupDescription("Create, update, and track customer orders.");

The composed description is **Summary** + a blank line + Description when both are set, or the summary/description alone when only one is set. Group text is written only to tags the endpoints actually carry, and an existing tag description is never overwritten. AddDefaultsDocumentTransformer() registers the transformer automatically.

⚠️ Known issue (v10.3.0): The standalone AddGroupTagsDocumentTransformer(IDictionary<string, string> tags) method requires a tags argument but ignores it — group text comes from the route group's metadata. Use AddDefaultsDocumentTransformer() until this is corrected.

Configuration

The transformers are configured via appsettings.json. Below are the details for the available settings classes.

OpenApiInfoSettings

Used by DocumentInfoTransformer to populate the document's info object.

appsettings.json Section: OpenApiInfoSettings

Property Type Description
UiReferenceEndpoint string The endpoint where the Scalar API reference UI is mapped. Defaults to "/".
Title string The title of the API.
Summary string A short summary of the API. Populated into the document since v10.1.1.
Version string The version of the API.
Description string A short description of the API.
TermsOfService string (URI) A URL to the Terms of Service for the API.
Contact OpenApiContactSettings (object) The contact information for the exposed API. See details below.
License OpenApiLicenseSettings (object) The license information for the exposed API. See details below.
OpenApiContactSettings
Property Type Description
Name string The identifying name of the contact person/organization.
Email string The email address of the contact person/organization.
Url string (URI) The URL pointing to the contact information.
OpenApiLicenseSettings
Property Type Description
Name string The license name used for the API.
Identifier string An SPDX license expression for the API. The identifier field is mutually exclusive of the url field.
Url string (URI) A URL to the license used for the API.

HeadersParameterSettings

Used by HeadersParameterTransformer to add common headers to requests and responses.

appsettings.json Section: OpenApiHeaders

Property Type Description
RequestHeaders List<[HeaderDefinition](#headerdefinition)> A list of header definitions to add to all API requests.
ResponseHeaders List<[HeaderDefinition](#headerdefinition)> A list of header definitions to add to all API responses.
HeaderDefinition

Represents a single header to be added to the OpenAPI specification.

Property Type Default Description
Name string "" The name of the header (e.g., "x-request-id").
Description string "" A description of the header's purpose.
Required bool true Specifies if the header is required.
Type JsonSchemaType String The schema type for the header value (e.g., "String", "Integer").
Format string? null The format of the header value (e.g., "uuid", "date-time"). The default header definitions use "uuid".
Value object? null An example value for the header.

Example appsettings.json

{
  "OpenApiInfoSettings": {
    "Title": "My Awesome API",
    "Version": "v1.0.0",
    "Summary": "A brief and catchy summary of the API.",
    "Description": "This is a more detailed description of the API. It can include **Markdown** for rich text formatting, explaining what the API does, its main features, and how to get started.",
    "TermsOfService": "https://example.com/terms",
    "Contact": {
      "Name": "API Support Team",
      "Url": "https://example.com/support",
      "Email": "support@example.com"
    },
    "License": {
      "Name": "MIT License",
      "Url": "https://opensource.org/licenses/MIT"
    }
  },
  "OpenApiHeaders": {
    "RequestHeaders": [
      {
        "Name": "x-request-id",
        "Description": "A unique identifier for the API call, used for tracing.",
        "Required": true
      }
    ]
  }
}

🔗 Dependencies

Usage

The easiest way to get started is by using the provided extension methods to register the various transformers and filters.

// Program.cs

using RA.Utilities.OpenApi.Extensions;
using RA.Utilities.OpenApi.Settings;

var builder = WebApplication.CreateBuilder(args);

// 1. (Optional) Configure settings from appsettings.json for the transformers.
builder.Services.Configure<OpenApiInfoSettings>(builder.Configuration.GetSection(OpenApiInfoSettings.AppSettingsKey));
builder.Services.Configure<HeadersParameterSettings>(builder.Configuration.GetSection(HeadersParameterSettings.AppSettingsKey));

// 2. Add OpenAPI services and register the transformers.
builder.Services.AddOpenApi(options =>
{
    // Default transformers (DocumentInfo, BearerSecurity, Headers, HealthChecks, GroupTags)
    // and the value object schema definitions.
    options.AddDefaultsDocumentTransformer();

    // 3. Register operation transformers for more granular control.
    options.AddDefaultResponsesOperationTransformer();

    // 4. Register FluentValidation schema enrichment.
    options.AddFluentValidationRules();
});

var app = builder.Build();

// 5. Map the OpenAPI document endpoint (e.g. /openapi/v1.json).
app.MapOpenApi();
// Optional: map an interactive API reference UI (e.g. Scalar) over the document.

app.MapGet("/weatherforecast", () => "Hello World!")
   .WithName("GetWeatherForecast");

app.Run();

With these transformers enabled, your API reference UI will show predefined response schemas for common status codes and standardized request headers on all endpoints.

Utilities

OpenApiOperationUtilities

The OpenApiOperationUtilities class is a static helper that provides methods for programmatically adding examples to requests and responses within an OpenApiOperation. This is particularly useful when creating custom IOpenApiOperationTransformer implementations where you need to add dynamic or complex examples to specific endpoints.

Key Functions:
  • AddRequestExample(...): Attaches a named example to the request body of an operation for a given media type (defaults to application/json).
  • AddRequestExamples(...): Attaches multiple named examples to the request body of an operation.
  • AddResponseExample(...): Attaches a named example to a specific HTTP status code response for an operation. This is great for showing what a successful response looks like or detailing the structure of a specific error.
  • AddGeneralErrorResponse(...): A specialized shortcut method that adds a pre-defined example for a 500 Internal Server Error.
  • AddResponseExamples(...): Attaches multiple named response examples, each with its own status code, to an operation.

Behavior (v10.3.1): AddRequestExample and AddResponseExample create the media type's Examples dictionary when it is empty, so examples are added even when the operation had none. AddResponseExample requires the operation to already define the target status code with a Content entry for the media type — otherwise it throws NullReferenceException (it returns silently when the status code itself is absent). AddRequestExample skips silently when the request body or media type is absent.

Limitation: AddResponseExamples currently ignores the per-item OpenApiResponseExample.MediaType and always uses application/json. Use AddResponseExample directly for other media types.

Example Usage in a Custom Operation Transformer
// Add a single request example
OpenApiOperationUtilities.AddRequestExample(operation, "CreateProduct",
    new OpenApiExample
    {
        Summary = "A new product",
        Value = JsonSerializer.SerializeToNode(new { Name = "Widget", Price = 9.99m })
    });

// Add a response example for a specific status code
OpenApiOperationUtilities.AddResponseExample(operation, StatusCodes.Status200OK,
    "ProductResponse",
    new OpenApiExample
    {
        Summary = "Product created",
        Value = JsonSerializer.SerializeToNode(new { Id = 1, Name = "Widget", Price = 9.99m })
    });

Additional Documentation

For more information on how this package fits into the larger RA.Utilities ecosystem, please see the main repository documentation.

Contributing

Contributions are welcome! If you have a suggestion or find a bug, please open an issue to discuss it.

Pull Request Process

  1. Fork the Repository: Start by forking the RA.Utilities repository.
  2. Create a Branch: Create a new branch for your feature or bug fix from the main branch. Please use a descriptive name (e.g., feature/add-security-transformer or fix/readme-typo).
  3. Make Your Changes: Write your code, ensuring it adheres to the existing coding style. Add or update XML documentation for any new public APIs.
  4. Update README: If you are adding new functionality, please update the README.md file accordingly.
  5. Submit a Pull Request: Push your branch to your fork and open a pull request to the main branch of the original repository. Provide a clear description of the changes you have made.

Coding Standards

  • Follow the existing coding style and conventions used in the project.
  • Ensure all public members are documented with clear XML comments.
  • Keep changes focused. A pull request should address a single feature or bug.

Thank you for contributing!

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.3.1 117 11/1/2026
10.3.0 107 10/28/2026
10.2.1 104 10/19/2026
10.2.0 116 10/18/2026
10.1.0 108 10/11/2026
10.0.11 127 9/28/2026
10.0.8 167 4/25/2026
10.0.7 148 3/24/2026
10.0.6 177 1/7/2026
10.0.5 239 12/23/2025
10.0.4 329 12/18/2025
10.0.3 354 12/17/2025
10.0.2 333 12/17/2025
10.0.1 195 12/12/2025
10.0.0 265 11/24/2025
10.0.0-rc.2 239 10/30/2025