DefaultResponsesOperationTransformer
Namespace: RA.Utilities.OpenApi.OperationTransformers
The DefaultResponsesOperationTransformer is an IOpenApiOperationTransformer that automatically adds a standardized 500 Internal Server Error response to every API operation in your OpenAPI document.
🎯 Purpose
The main goals of this transformer are:
- Standardize 500 Error Responses: It ensures that every endpoint in your API documentation clearly and consistently shows that it can produce a structured
ErrorResponsefor an internal server error. It uses theErrorResponsemodel from theRA.Utilities.Api.Responsepackage (namespaceRA.Utilities.Api.Response) to define the schema. - Reduce Boilerplate Annotations: It eliminates the need for developers to manually add a
[ProducesResponseType(typeof(ErrorResponse), 500)]attribute to every single API endpoint. The transformer handles this globally. - Operation-Level Granularity: As an
IOpenApiOperationTransformer, it integrates perfectly into the OpenAPI generation pipeline at the operation level, making it a clean and efficient way to apply this specific rule.
In essence, while a DocumentTransformer is for broad, document-wide changes, an OperationTransformer like this one provides a scalpel for making precise, repeated changes to every endpoint.
⚙️ How It Works
- Ensures the operation has a
Responsesdictionary. - Checks for an existing
"500"response and returns without changes if it is already present. - Adds a
"500"response documented asapplication/json, using the generated schema forResponse<ErrorResponse>and a default example built fromnew ErrorResponse().
Because the transformer runs per operation, any endpoint that already documents a custom 500 response keeps it.
🚀 Usage
To use the transformer, register it as an IOpenApiOperationTransformer in your Program.cs.
// Program.cs
using RA.Utilities.OpenApi.Extensions;
var builder = WebApplication.CreateBuilder(args);
// ... other services
builder.Services.AddOpenApi(options =>
{
options.AddDefaultResponsesOperationTransformer();
});
var app = builder.Build();
// ...
This ensures that every API endpoint documented in your Swagger/OpenAPI UI will correctly show the standard 500 error response, improving the clarity and completeness of your API contract with minimal effort.