ASP.NET - API Documentation with Swagger and OpenAPI Customization
API documentation is an essential part of modern web application development. It helps developers understand how an API works, what endpoints are available, what parameters need to be sent, and what responses can be expected. Instead of manually writing documentation that can become outdated over time, ASP.NET Core provides excellent support for automatically generating API documentation using Swagger and OpenAPI.
Swagger is a collection of tools that helps developers design, document, test, and consume REST APIs. OpenAPI is the official specification that defines how REST APIs should be described. In ASP.NET Core, Swagger generates interactive documentation based on the application's controllers and endpoints, allowing developers to test APIs directly from a web browser.
What is OpenAPI?
OpenAPI is a standardized specification for describing REST APIs. It defines every aspect of an API, including:
-
Available endpoints
-
HTTP methods
-
Request parameters
-
Request body structure
-
Response formats
-
Authentication methods
-
Error responses
-
API version information
Since OpenAPI follows a standard format, many tools can automatically generate client libraries, server code, documentation, and testing tools from the same specification.
What is Swagger?
Swagger is a toolset built around the OpenAPI specification. It provides features such as:
-
Automatic API documentation
-
Interactive API testing
-
API schema generation
-
Client SDK generation
-
Request and response visualization
In ASP.NET Core, Swagger is commonly implemented using the Swashbuckle.AspNetCore package.
Benefits of Swagger Documentation
Using Swagger provides several advantages.
Automatic Documentation
Documentation is generated directly from the API source code. Whenever the API changes, the documentation updates automatically.
Interactive Testing
Developers can send requests directly from the browser without using external tools like Postman.
Better Developer Experience
Clear documentation makes it easier for new developers to understand the API.
Faster Integration
Frontend developers and third-party developers can understand the API without reading the backend code.
Reduced Documentation Errors
Since documentation is generated from the code itself, inconsistencies between implementation and documentation are minimized.
Installing Swagger in ASP.NET Core
Swagger can be added using the NuGet Package Manager.
Install-Package Swashbuckle.AspNetCore
Or using the .NET CLI:
dotnet add package Swashbuckle.AspNetCore
Configuring Swagger
Swagger services are registered in the Program.cs file.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Next, enable Swagger middleware.
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.Run();
After running the application, Swagger UI becomes available.
Example:
https://localhost:5001/swagger
The page displays all available API endpoints with complete documentation.
Adding API Information
Swagger allows developers to provide metadata about the API.
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Student Management API",
Version = "v1",
Description = "API for managing student information",
Contact = new OpenApiContact
{
Name = "Support Team",
Email = "[email protected]"
}
});
});
This information appears at the top of the Swagger documentation page.
Documenting API Endpoints
Suppose there is a controller.
[ApiController]
[Route("api/[controller]")]
public class StudentController : ControllerBase
{
[HttpGet]
public IActionResult GetStudents()
{
return Ok();
}
}
Swagger automatically identifies:
-
Route
-
HTTP method
-
Controller name
-
Response type
It displays them in a structured format.
Adding XML Comments
Code comments can be included in the generated documentation.
Example:
/// <summary>
/// Returns all students.
/// </summary>
/// <returns>List of students</returns>
[HttpGet]
public IActionResult GetStudents()
{
return Ok();
}
Enable XML documentation in the project settings and configure Swagger.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
The summary appears directly inside Swagger UI.
Documenting Parameters
Swagger automatically documents endpoint parameters.
[HttpGet("{id}")]
public IActionResult GetStudent(int id)
{
return Ok();
}
Swagger displays:
Parameter
id
Type
integer
Required
Yes
Developers can enter the value directly and execute the request.
Documenting Request Body
Example:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Controller:
[HttpPost]
public IActionResult AddStudent(Student student)
{
return Ok(student);
}
Swagger automatically generates a JSON request body.
{
"id": 1,
"name": "John",
"age": 20
}
Users can edit the JSON before sending the request.
Documenting Response Types
Response information can be specified explicitly.
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{id}")]
public IActionResult GetStudent(int id)
{
return Ok();
}
Swagger displays possible responses.
-
200 OK
-
404 Not Found
This helps API consumers understand expected outcomes.
Organizing APIs into Groups
Large applications may contain many controllers.
Swagger supports grouping.
[ApiExplorerSettings(GroupName = "Students")]
Different groups appear as separate sections in the documentation.
Examples:
-
Students
-
Employees
-
Products
-
Orders
This improves readability.
Adding Authentication Support
If an API uses JWT authentication, Swagger can include an authorization button.
Configuration:
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer",
new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header
});
});
Swagger UI displays an Authorize button where users can enter a JWT token. Once authenticated, secured endpoints can be tested directly from the interface without manually adding headers to each request.
API Versioning in Swagger
Applications often evolve over time, requiring multiple API versions to coexist.
Example:
Version 1
/api/v1/students
Version 2
/api/v2/students
Swagger can generate separate documentation pages for each version, allowing developers to maintain backward compatibility while documenting new features independently.
Customizing Swagger UI
Swagger UI offers several customization options to match project requirements.
Common customizations include:
-
Changing the page title
-
Displaying a custom logo
-
Setting the default expansion of endpoints
-
Sorting controllers alphabetically
-
Sorting operations by HTTP method
-
Enabling or disabling the request duration display
-
Applying custom CSS or JavaScript for branding
These changes improve usability and create a more professional documentation interface.
Testing APIs Using Swagger
Swagger UI provides an interactive environment for testing APIs.
The typical workflow is:
-
Select an endpoint.
-
Click Try it out.
-
Enter required parameters or request body.
-
Click Execute.
-
View the response status code, response body, response headers, and execution time.
This eliminates the need for separate API testing tools during development and simplifies debugging.
Generating OpenAPI JSON
Swagger also exposes the complete OpenAPI specification as a JSON document.
Example URL:
https://localhost:5001/swagger/v1/swagger.json
This JSON file can be used to:
-
Generate client SDKs in various programming languages.
-
Import the API into testing tools.
-
Create developer portals.
-
Integrate with API gateways.
-
Perform automated validation and documentation updates.
Best Practices
To create effective API documentation:
-
Write clear and meaningful summaries for controllers and actions.
-
Document all request parameters and response types.
-
Include realistic example request and response payloads.
-
Group related endpoints logically.
-
Secure Swagger in production environments if necessary.
-
Keep documentation synchronized with code changes.
-
Use API versioning for breaking changes.
-
Provide descriptions for authentication and authorization requirements.
-
Document common error responses with appropriate status codes.
Conclusion
Swagger and OpenAPI play a crucial role in modern ASP.NET Core API development by providing accurate, interactive, and automatically generated documentation. They simplify API testing, improve collaboration between backend and frontend developers, reduce maintenance effort, and help ensure that API documentation stays aligned with the implementation. By taking advantage of customization features, authentication support, API versioning, and XML comments, developers can create comprehensive and user-friendly API documentation that enhances the overall development experience and makes APIs easier to understand, integrate, and maintain.