RA.Utilities.OpenApi
10.0.6
Prefix Reserved
dotnet add package RA.Utilities.OpenApi --version 10.0.6
NuGet\Install-Package RA.Utilities.OpenApi -Version 10.0.6
<PackageReference Include="RA.Utilities.OpenApi" Version="10.0.6" />
<PackageVersion Include="RA.Utilities.OpenApi" Version="10.0.6" />
<PackageReference Include="RA.Utilities.OpenApi" />
paket add RA.Utilities.OpenApi --version 10.0.6
#r "nuget: RA.Utilities.OpenApi, 10.0.6"
#:package RA.Utilities.OpenApi@10.0.6
#addin nuget:?package=RA.Utilities.OpenApi&version=10.0.6
#tool nuget:?package=RA.Utilities.OpenApi&version=10.0.6
RA.Utilities.OpenApi
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
- Dependencies
- Document Transformers
DocumentInfoTransformerBearerSecuritySchemeTransformerHeadersParameterTransformerBearerSecurityDocumentTransformer
- Operation Transformers
DefaultResponsesOperationTransformer
- Schema Filters (as Document Transformers)
PolymorphismDocumentTransformer
- Utilities
OpenApiOperationUtilities
- Configuration
OpenApiInfoSettingsHeadersParameterSettings- Example
appsettings.json
- Usage
- Contributing
Getting started
Install the package via the .NET CLI:
dotnet add package RA.Utilities.OpenApi
Or through the NuGet Package Manager in Visual Studio.
Default Transformers
This package includes a set of default 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:
- Reads from Configuration: It uses
OpenApiInfoSettingsto bind to a configuration section (e.g.,OpenApi:Info). - Populates
OpenApiInfo: It sets theTitle,Version,Description,Contact, andLicensefields in the generated document. - Simplifies Customization: Allows you to update your API's documentation details without changing any code.
BearerSecuritySchemeTransformer
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:
- Detects JWT Authentication: It checks if an authentication scheme named
BearerorBearerTokenis present. - Adds Security Scheme: If detected, it adds the standard JWT Bearer security definition to the document's components.
- Reduces Boilerplate: Eliminates the need to manually configure
AddSecurityDefinitionandAddSecurityRequirementinSwaggerGenOptionsfor 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:
- Adds Request Headers: It adds headers like
x-request-idas parameters to all API requests. This documents the need for clients to provide a unique identifier for each call. - Adds Response Headers: It adds headers like
x-request-idandtrace-idto 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.
ResponsesDocumentTransformer
This transformer automatically adds standardized OpenAPI responses for common HTTP status codes like 400, 404, 409, and 500. It uses the response models from RA.Utilities.Api.Results to generate the schema for these error responses.
What it does:
- Standardizes Error Responses: Ensures that your OpenAPI documentation accurately reflects the structured error responses (
BadRequestResponse,NotFoundResponse,ConflictResponse,ErrorResponse) that your API produces. - Reduces Annotations: Eliminates the need to manually add
[ProducesResponseType]attributes for these common errors on every single endpoint.
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.Results 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:
- Standardizes Error Responses: Ensures that your OpenAPI documentation accurately reflects the structured error responses (
ErrorResponse) that your API produces. - Reduces Annotations: Eliminates the need to manually add
[ProducesResponseType]attributes for these common errors on every single endpoint. - Operation-Level Granularity: As an
IOpenApiOperationTransformer, it integrates seamlessly with Swashbuckle's operation-level processing pipeline.
Schema Filters (as Document Transformers)
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:
- Finds the Base Schema: It locates the schema for a specified base type in the OpenAPI document.
- Generates Derived Schemas: It ensures that schemas for all specified derived types are present in the document, creating them if necessary.
- Adds
oneOfanddiscriminator: It modifies the base schema to use theoneOfkeyword, listing all derived types, and adds adiscriminatorobject to tell clients how to determine the correct type based on a property (e.g.,"type"). - 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, you need to instantiate it with the required parameters and register it in Program.cs.
// Program.cs
builder.Services.AddOpenApiDocumentTransformer(new PolymorphismDocumentTransformer(
polymorphismPropertyName: "Error", // The name of the base schema
typesToInclude: new() // A dictionary of derived types
{
{ "NotFound", typeof(NotFoundResponse) },
{ "Conflict", typeof(ConflictResponse) },
}
));
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: OpenApi:Info
| Property | Type | Description |
|---|---|---|
| Title | string |
The title of the API. |
| 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. |
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. |
| 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](#eaderdefinition)> |
A list of header definitions to add to all API requests. |
| ResponseHeaders | List<[HeaderDefinition](#eaderdefinition)> |
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 |
"uuid" |
The format of the header value (e.g., "uuid", "date-time"). |
| Value | object |
null |
An example value for the header. |
Example appsettings.json
{
"OpenApiInfoSettings": {
"Info": {
"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
Recommended: Using Default Transformers
The easiest way to get started is by using the provided extension methods to register the various transformers and filters.
// Program.cs
using Microsoft.OpenApi.Models;
using RA.Utilities.OpenApi.DocumentTransformers;
using RA.Utilities.OpenApi.Extensions;
using RA.Utilities.OpenApi.OperationTransformers;
using RA.Utilities.OpenApi.SchemaFilters;
using RA.Utilities.OpenApi.Settings;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
// 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.
// Use AddSwaggerGen() for controller-based APIs or more advanced scenarios.
builder.Services.AddOpenApi()
.AddDefaultsDocumentTransformer();
// 3. Register additional document transformers individually.
builder.Services.AddOpenApiDocumentTransformer<BearerSecurityDocumentTransformer>();
// 4. Register operation transformers for more granular control.
builder.Services.AddOpenApiOperationTransformer<DefaultResponsesOperationTransformer>();
// 5. If using Swashbuckle (AddSwaggerGen), you can add schema filters.
// This is shown for completeness. AddSwaggerGen() is needed for this to work.
builder.Services.AddSwaggerGen(options =>
{
options.SchemaFilter<PolymorphismDocumentTransformer>();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// 6. Map the OpenAPI document endpoints.
app.MapOpenApi();
app.MapGet("/weatherforecast", () => "Hello World!")
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
With this transformer enabled, your Swagger UI will now show predefined response schemas for 400, 404, 409, and 500 status codes on all endpoints, matching the structure of your RA.Utilities.Api.Results models.
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 IOperationFilter 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 examples to a specific HTTP status code response.
Example Usage in an IOperationFilter
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
- Fork the Repository: Start by forking the RA.Utilities repository.
- Create a Branch: Create a new branch for your feature or bug fix from the
mainbranch. Please use a descriptive name (e.g.,feature/add-security-transformerorfix/readme-typo). - Make Your Changes: Write your code, ensuring it adheres to the existing coding style. Add or update XML documentation for any new public APIs.
- Update README: If you are adding new functionality, please update the
README.mdfile accordingly. - Submit a Pull Request: Push your branch to your fork and open a pull request to the
mainbranch 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 | Versions 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. |
-
net10.0
- FluentValidation (>= 12.1.1)
- Microsoft.AspNetCore.OpenApi (>= 10.0.0)
- RA.Utilities.Api.Results (>= 10.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.