How to document ASP.NET Web API with Swagger?
Documenting ASP.NET Web API 2 with Swagger and Swashbuckle, XML comments, response contracts, and Swagger UI for an explicit API contract.
How to document ASP.NET Web API with Swagger?
An Application Programming Interface (API) is a front door for other applications, but a front door without a sign makes visitors guess where to go. Consumers need to know the available resources, inputs, responses and error conditions before they can integrate safely. If this information is existing only in a meeting or in a developer’s memory, the team will spend time answering the same questions and consumers may call the API incorrectly.
Swagger 2.0 provides a machine-readable description of an HTTP API, and Swashbuckle can generate that description for ASP.NET Web API 2. In this article, we are going to see how to add Swagger to a .NET Framework Web API project, improve the generated descriptions and use the Swagger UI for a pulse check.
We can document an API in two common ways:
| Approach | Pros | Cons |
|---|---|---|
| Hand-written document | + Full control of explanation<br>+ Can include broad business context | − Drifts from the implementation<br>− Repeated maintenance work |
| Generated Swagger document | + Close to the API contract<br>+ Supports tooling and exploration | − Needs useful code metadata<br>− Does not explain every business decision |
TL;DR Summary
- API documentation should be produced close to the API implementation.
- Swagger 2.0 describes resources, operations, parameters, responses and security.
- Swashbuckle integrates Swagger generation with ASP.NET Web API 2.
- XML comments and response attributes make generated documentation more useful.
- Swagger UI is useful for exploration, but it is not a replacement for automated tests.
- Do not publish internal endpoints or secrets in a public documentation endpoint.
Challenges
Documentation drift
A manually maintained document can say that an endpoint accepts one field while the code accepts another. Consumers follow the document, receive an error and raise support tickets. This creates a ripple effect between the API team and every dependent team.
Unclear contracts
An HTTP status code without an explanation is not enough for a consumer to decide what to do. A client must know whether a missing article is a 404, invalid input is a 400, or a server failure is a 500. A good contract makes the reactive support conversation smaller.
Unsafe exploration
Consumers need a quick way to try a request, but an interactive page can call a real endpoint. We must protect the documentation and use non-production data for exploration, otherwise a test request may change a customer record.
What is Swagger?
Swagger is a specification for describing HTTP APIs in a structured document which tools can read.
In simple terms, Swagger is a common language between an API team and its consumers. The description can be used to generate a human-friendly UI, client code or contract checks. The specification describes the API, it does not replace the API implementation.
Why API documentation is important?
Documentation reduces ambiguity and improves collaboration. Consider a news article API: a consumer can see that GET /api/articles/{id} returns an article, the id is required, and a missing article returns 404. The consumer can build the correct flow without asking the API developer for each detail.
How to configure Swagger?
The following diagram depicts ASP.NET Web API producing a Swagger document and Swagger UI consuming it,

Option1: Generated Swagger with Swashbuckle
Steps to Implement:
Follow the following instructions to add Swagger to an ASP.NET Web API 2 application.
-
Open the Web API 2 project in Visual Studio 2015.
-
Install Swashbuckle from NuGet.
Install-Package Swashbuckle -
Confirm that the package added a Swagger configuration class and the startup registration.
-
Enable XML documentation in the project properties.
Project Properties > Build > XML documentation file -
Add XML comments to the controller and action methods.
/// <summary> /// Returns a news article by identifier. /// </summary> /// <param name="id">The article identifier.</param> public IHttpActionResult Get(int id) { Article article = repository.Find(id); if (article == null) return NotFound(); return Ok(article); } -
Configure Swashbuckle to include the XML comments file, replacing the input place holders with actual values.
c.IncludeXmlComments( HttpContext.Current.Server.MapPath( "<xml documentation file name>")); -
Add response descriptions to the actions.
[ResponseType(typeof(Article))] [SwaggerResponse(HttpStatusCode.NotFound, "Article was not found")] public IHttpActionResult Get(int id) { // implementation } -
Build the application and start it locally.
-
Open the generated Swagger UI.
http://localhost:<port>/swagger/ -
Just to pulse check, expand an operation, enter a known article identifier and compare the response with the documented status code and schema.
Note: Replace the input place holders with actual values. Do not put a production API key or customer information into an example request.
-
Publish the Swagger document with the same release as the API and review it when an endpoint contract changes.
Documentation as a contract
The generated description should explain the business meaning, not only the CLR type. A property named id is less useful than articleId if consumers cannot infer which resource it identifies. Use consistent naming and document nullable fields, allowed values and pagination.
Swagger UI can help a new developer understand the API, but contract tests are still required. The API should return stable status codes and should not expose stack traces. Authentication details must be documented at the level consumers need, while internal credentials and connection information must never appear in the document.
It is also important to keep the documented examples realistic. If an article endpoint returns a list in production but the example shows one object, consumers will build the wrong deserialization code. Add examples for empty results, validation failures and pagination when those cases are part of the contract, because the unhappy path is where integration usually gets delayed.
Option2: Hand-written document
A hand-written document is still useful for business workflows, migration notes and decisions which cannot be inferred from code. Keep it beside the generated contract and review it when the API changes. It should complement Swagger, not become the only source of endpoint truth.
Documenting a real Web API contract
Find below an example of a Web API action which is returning a resource and explicit status codes,
[RoutePrefix("api/articles")]
public class ArticlesController : ApiController
{
[HttpGet]
[Route("{id:int}", Name = "GetArticle")]
public IHttpActionResult Get(int id)
{
Article article = repository.Find(id);
if (article == null)
return NotFound();
return Ok(article);
}
[HttpPost]
[Route("")]
public IHttpActionResult Create(CreateArticleRequest request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
Article article = service.Create(request);
return CreatedAtRoute(
"GetArticle",
new { id = article.Id },
article);
}
}
The XML comments and response attributes should explain the request and the possible result, not only repeat the method name. Add a response description for 400, 404 and 201, because consumers are requiring this information to implement the correct branch.
API documentation checklist
- Must Do: Generate documentation from the same commit as the API.
- Must Do: Document authentication and required scopes without publishing secrets.
- Must Do: Document pagination, filtering and empty result behaviour.
- Don’t: Expose internal controllers or test endpoints on the production Swagger document.
- Don’t: Return stack traces through Swagger UI.
- Be mindful: Swagger UI is useful for a pulse check, but automated contract and integration tests are still required.
In our case, a news article API should show whether GET /api/articles returns an empty list or 404, and it should show which field is required to create an article. A consumer then can build the client without sending repeated questions to the API team, hence the feedback loop is becoming shorter.
Versioning and publishing
When a breaking contract change is required, version the Web API route or document rather than silently changing the existing response. Keep the Swagger document for the same version as the deployed API, because a consumer is otherwise reading one contract and calling another. For internal APIs, protect the Swagger endpoint with the same authentication boundary as the API or expose it only in the required environment.
A generated document is not making a poor contract healthy out of the box. We should review naming, status codes, error shapes and examples during code review. The aim is proactive communication, so consumers are understanding the change before it is impacting their integration.
Wrap up
In this article, we have looked at the need for API documentation, installed Swashbuckle, enabled XML comments, documented response contracts and used Swagger UI with ASP.NET Web API 2. I hope this article provided you some insights into Swagger documentation. In the next article, I will walk you through securing ASP.NET Web API with OAuth 2.0 bearer tokens using OWIN.
Related Posts
Getting started with Docker - Part 1
Getting started with Docker through images, containers, Docker Toolbox, Docker Machine, host addresses, and basic Docker 1.x commands for practical first steps.
How to secure ASP.NET Web API with OAuth 2.0 bearer tokens (OWIN)?
Securing ASP.NET Web API with OAuth bearer tokens through OWIN, covering token endpoints, external JWT issuers, bearer validation, claims, and authorization roles.
How to store files in Azure Blob Storage from ASP.NET?
Storing files in Azure Blob Storage from ASP.NET, including containers, validation, uploads, private file serving, and separating file metadata.