November 6, 2020
When building modern web services, providing clear and accessible API documentation is crucial for ensuring smooth integration and usage. With .NET Core and OpenAPI (previously known as Swagger), you can automatically generate interactive and self-updating documentation for your RESTful APIs, saving time and improving the developer experience.
In this post, we’ll explore how to build self-documented RESTful APIs with .NET Core and OpenAPI, making your API development process more efficient and accessible to users.
1. Introduction to OpenAPI and Swagger
OpenAPI is a specification for describing RESTful APIs in a standard format. It allows both humans and computers to understand the capabilities of a web service without having access to the source code. Swagger is a set of tools built around the OpenAPI specification that facilitates API documentation, testing, and client generation.
The Swagger UI provides an interactive web interface that allows developers and consumers to explore API endpoints, make requests, and see the results, all from within the browser.
In .NET Core, Swagger can be easily integrated into your Web API project to automatically generate this documentation.
2. Setting Up OpenAPI in a .NET Core Web API Project
To get started, let’s first set up a simple .NET Core Web API project. If you don’t have one already, you can create it using the following command:
dotnet new webapi -n MyApi
cd MyApi
Once you have your Web API project, we will need to add Swashbuckle.AspNetCore, which is the library that integrates Swagger/OpenAPI with .NET Core.
a. Installing Swagger/OpenAPI with Swashbuckle
Run the following command to install Swashbuckle:
dotnet add package Swashbuckle.AspNetCore
b. Configuring Swagger in Startup.cs
After installing Swashbuckle, you need to add some configuration to enable Swagger in your API. Open the Startup.cs file and make the following changes.
In the ConfigureServices
method, add the following line to register Swagger:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1",
Description = "An example API for demonstrating OpenAPI and Swagger in .NET Core"
});
});
}
Next, in the Configure
method, add the Swagger middleware to enable the Swagger UI:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.)
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
c.RoutePrefix = string.Empty; // To serve Swagger UI at the root (e.g. http://localhost:5000)
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
This configuration does two things:
- It generates the Swagger specification at
/swagger/v1/swagger.json
. - It serves the Swagger UI at the root of the API (e.g.,
http://localhost:5000
).
3. Adding Documentation to Your API Endpoints
Now that Swagger is set up, let’s look at how we can add useful documentation to our API endpoints. In .NET Core, you can easily provide metadata for your API by using XML comments and attributes.
a. Adding XML Comments
XML comments provide additional context about your API’s methods and parameters. To enable XML documentation in your project, right-click on your project file and select Properties. Under the Build tab, check the box for XML documentation file.
This will generate an XML file that contains the documentation for your methods, which Swagger can read to provide more detailed descriptions.
You can now add XML comments to your controller actions and models:
/// <summary>
/// Retrieves a user by their ID.
/// </summary>
/// <param name="id">The ID of the user</param>
/// <returns>A user object</returns>
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
// Retrieve and return the user
var user = _userService.GetUserById(id);
return Ok(user);
}
b. Using Attributes for Additional Metadata
You can use Swagger-specific attributes to provide further details for your API. For example, the [ProducesResponseType]
attribute helps document the possible HTTP response codes for an endpoint:
/// <summary>
/// Creates a new user.
/// </summary>
/// <param name="user">The user data to create</param>
/// <returns>The created user</returns>
[HttpPost]
[ProducesResponseType(typeof(User), 201)]
[ProducesResponseType(400)]
public IActionResult CreateUser([FromBody] User user)
{
var createdUser = _userService.CreateUser(user);
return CreatedAtAction(nameof(GetUser), new { id = createdUser.Id }, createdUser);
}
In this example, we’ve added a 201 Created
response type for successful user creation and a 400 Bad Request
response for invalid input.
4. Exploring the Swagger UI
Now, when you run your API and navigate to the root of your project (e.g., http://localhost:5000
), you should see the Swagger UI. This interface allows you to explore your API, view the available endpoints, and even execute API calls directly from the browser.
5. Benefits of OpenAPI and Swagger in .NET Core
- Self-Documenting APIs: With Swagger, your APIs come with built-in documentation, which is automatically generated from your code.
- Interactive Documentation: The Swagger UI provides an interactive web interface for testing your API, making it easier for developers to understand and use your API.
- API Standardization: OpenAPI provides a standard format for describing APIs, making it easier to integrate with other services and tools, such as API testing tools or client libraries.
- Better Developer Experience: By using Swagger, you provide an API that is easy to explore, making it more developer-friendly.
6. Conclusion
In this post, we have seen how to integrate OpenAPI with .NET Core to build self-documented RESTful APIs. We’ve covered how to set up Swagger, add metadata using XML comments and attributes, and explore the powerful Swagger UI.
By incorporating Swagger and OpenAPI into your .NET Core Web API projects, you can improve the developer experience, automate documentation, and create APIs that are easier to integrate and test. Whether you are building a small service or a large-scale system, these tools can save you time and effort while enhancing the quality of your APIs.
Happy coding, and enjoy building your self-documented APIs with .NET Core and OpenAPI!