| Versioning WEB API in .net core :👈 | 👉:Unit-Testing-in-ASP-NET-Core |
📘 Swagger / OpenAPI Documentation in ASP.NET Core |
🔍 What is Swagger?
Swagger (now known as OpenAPI) is a specification for documenting RESTful APIs. It provides a user-friendly interface to explore and test endpoints, view request/response schemas, and generate client SDKs.
Swagger (OpenAPI) documentation is a standard, language-agnostic specification for describing REST APIs. It provides a blueprint that allows both humans and computers to understand an API's capabilities without accessing the source code. In ASP.NET Core, this is implemented using a NuGet package and middleware.
Key Concepts
OpenAPI vs. Swagger:
- OpenAPI: The formal specification for describing the API in a machine-readable JSON or YAML file (e.g., openapi.json).
- Swagger: A set of tools from SmartBear that implement the OpenAPI Specification. Swagger UI provides an interactive web interface for exploring and testing the API.
- Swashbuckle: A popular NuGet package that integrates Swagger into ASP.NET Core applications. It generates the OpenAPI JSON document and serves Swagger UI.
- Built-in OpenAPI support (.NET 9 and above): Uses Microsoft.AspNetCore.OpenApi for generating the OpenAPI spec. Swagger UI can still be added using Swashbuckle.AspNetCore.SwaggerUI.
🛠️ How to Set Up Swagger in ASP.NET Core
Example: Implementing Swagger with Swashbuckle
Step 1: Install the NuGet Package
dotnet add package Swashbuckle.AspNetCore
Step 2: Add and Configure Middleware
// Program.cs
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 3: Run and Test
Run your application and navigate to /swagger in your browser to access the interactive API documentation.
Step 4: Add XML Comments for Rich Documentation
Enable XML documentation in project settings, then configure Swagger to read the XML file.
// Program.cs
using System.Reflection;
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
Add Comments to Code
/// <summary>
/// A controller for managing products.
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
/// <summary>
/// Gets a list of all products.
/// </summary>
/// <returns>A list of products.</returns>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public IEnumerable<string> Get()
{
return new string[] { "Product 1", "Product 2" };
}
}
📄 Customize Swagger Documentation
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1",
Description = "Sample API for demonstration",
Contact = new OpenApiContact
{
Name = "Shivshanker",
Email = "shiv@example.com"
}
});
});
✅ When to Use Swagger
- Public APIs that need clear documentation
- Internal APIs for development and testing
- Generating client SDKs automatically
- Improving developer onboarding and collaboration
🚫 When Not to Use Swagger
- Highly secure APIs where exposing endpoints is risky
- Minimal APIs with very few endpoints
- Production environments without proper access control
🌟 Advantages
- Interactive UI for testing endpoints
- Auto-generated documentation from code
- Supports multiple versions and security schemes
- Improves API discoverability and usability
⚠️ Disadvantages
- May expose sensitive endpoints if not secured
- Requires maintenance as APIs evolve
- Can slow down startup if misconfigured
🧯 Precautions
- Restrict Swagger UI access in production
- Use authentication for protected endpoints
- Keep documentation updated with code changes
🧠 Best Practices
- Use XML comments to enrich endpoint descriptions
- Group endpoints by tags for clarity
- Document request/response models with annotations
- Enable versioning and document each version separately
| Versioning WEB API in .net core :👈 | 👉:Unit-Testing-in-ASP-NET-Core |