1. OpenAPI Overview
OpenAPI is a standardized specification used to describe REST APIs. In .NET, it integrates directly with ASP.NET Core using Swashbuckle or NSwag, enabling automatic API documentation, client generation, and contract validation.
2. Enabling OpenAPI in ASP.NET Core
ASP.NET Core ships with first-class OpenAPI support. Add the following registrations in Program.cs:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.Run();
3. Controller Automatically Exposed to OpenAPI
Any controller with routing attributes is scanned and added to the OpenAPI schema:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id) => new Product { Id = id, Name = "Laptop" };
}
4. Adding Schema Metadata With Data Annotations
OpenAPI automatically maps model properties and their constraints from attributes:
public class Product {
[Required]
public int Id { get; set; }
[StringLength(50)]
public string Name { get; set; }
}
5. Adding Custom OpenAPI Configuration
You can customize document title, version, and description:
builder.Services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo {
Title = "E-Commerce API",
Version = "v1",
Description = "API for product management"
});
});
6. Securing APIs With JWT Swagger UI
OpenAPI supports authentication definition, enabling header injection during testing:
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
In = ParameterLocation.Header,
Description = "JWT Authorization header",
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } },
Array.Empty<string>()
}
});
7. Producing and Consuming Specific Media Types
OpenAPI automatically documents response formats:
[Produces("application/json")]
[Consumes("application/json")]
[HttpPost]
public IActionResult Create(Product product) => Ok(product);
8. API Versioning With OpenAPI Support
Multiple versions can be generated using different documents:
c.SwaggerDoc("v2", new OpenApiInfo { Title = "E-Commerce API v2", Version = "v2" });
9. Generating Typed C# Client Using NSwag
NSwag CLI can create client SDKs with full type-safety:
nswag openapi2csclient /input:swagger.json /output:Client.cs
10. Using the Generated Typed Client
Client gives strongly typed methods instead of manual HttpClient:
var client = new ProductsClient("https://api.example.com");
var product = await client.GetProductAsync(10);
11. Contract-First Development Flow
You can design an API first using swagger.yaml, then generate controllers:
nswag openapi2cscontroller /input:api.yaml /output:Controllers
12. Automated Validation in CI/CD
OpenAPI documents can be validated during build:
openapi-generator-cli validate -i swagger.json
13. Using OpenAPI With Minimal APIs
.NET supports OpenAPI for minimal APIs as well:
app.MapGet("/hello", () => "Hello").WithOpenApi();
14. Adding XML Comments for Rich Documentation
Enable XML doc generation in .csproj:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
Then load in Swagger:
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "MyApi.xml"));
Summary
OpenAPI deeply enhances .NET API development by offering automatic documentation, contract-first workflows, strong typing through client generation, versioning support, built-in security schema handling, and CI-driven quality control. Combined with Swashbuckle or NSwag, it provides a complete, reliable, and scalable API development ecosystem for enterprise-grade applications.