Using Swagger to Document and Test Your C# REST API

Looking to improve your C# REST API documentation and testing? This guide on using Swagger will take your API development to the next level.

By Tim TrottC# ASP.Net MVC • January 22, 2024
841 words, estimated reading time 3 minutes.
Writing C# REST APIs

This article is part of a series of articles. Please use the links below to navigate between the articles.

  1. A Beginner's Guide to Building a REST API in C#
  2. Using Swagger to Document and Test Your C# REST API
  3. How to Add Authentication and Authorisation to C# REST APIs
  4. Error Handling and Exception Management in C# REST APIs
  5. Data Validation and Error Handling in REST APIs using C#
  6. Versioning Your C# REST API: Best Practices and Approaches
  7. Caching Strategies for Improved Efficiency in C# REST APIs
  8. How to Implement Rate Limiting in Your C# REST API
Using Swagger to Document and Test Your C# REST API

Swagger is a powerful tool that can significantly improve the documentation and testing of your C# REST API. In this beginner's tutorial, we'll explore how Swagger can accelerate your API development process, freeing up your time and increasing the overall quality of your API.

What is Swagger and Why is it Useful for Documenting and Testing REST APIs?

Swagger, a free and open-source software framework, empowers developers to create, describe, and test RESTful APIs. It provides a user-friendly interface that simplifies the process of defining the structure and behaviour of APIs, making them more understandable and consumable. With Swagger's interactive documentation, developers can easily explore and test API endpoints.

Swagger API Testing and Documentation Running On A Laptop
Using Swagger to Document and Test Your C# REST API

Swagger's Main Features and Capabilities

Some of the main features and capabilities of Swagger include:

  1. API Documentation: Swagger creates interactive documentation for your API, including endpoint details, request/response examples, and parameter explanations. This documentation is simple to share with other developers and can be used as a reference for future development.
  2. API Testing: Swagger allows you to test your API endpoints directly from the Swagger UI. This helps you ensure that your API is working properly and troubleshoot any possible difficulties.
  3. Code Generation: Based on your API description, Swagger can produce client SDKs in a variety of programming languages, including C#. Designing client applications that use your API can save you time and effort.
  4. Security Integration: Swagger supports a variety of authentication methods, including OAuth2 and API keys, to help you secure your API endpoints. The Swagger UI makes it simple to configure these security settings.
  5. Versioning and Change Management: Swagger has tools for managing API versions as well as describing differences between them. This can assist you in keeping track of API updates and ensuring that developers are informed of any significant changes.

Installing and Setting up Swagger in a C# Project

Follow these steps to install and set up Swagger in a C# project:

  1. Open your C# project in Visual Studio.
  2. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages".
  3. In the NuGet Package Manager, search for "Swashbuckle.AspNetCore" and install the package.
  4. Once the package is installed, open the Startup.cs file in your project.
  5. In the ConfigureServices method, add the following code to enable Swagger
    C#
    services.AddSwaggerGen(c =>
    {
      c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API Name", Version = "v1" });
    });
  6. In the Configure method, add the following code to enable Swagger UI:
    C#
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API Name v1");
    });
  7. Build and run your project. You should now be able to access the Swagger UI by navigating to "/swagger" in your web browser.

Add XML Documentation (Optional)

You can produce XML documentation for your API project if you wish to incorporate XML documentation comments in your Swagger documentation. Right-click your project, select Properties, Build, and tick the "XML documentation file" box. Then, reassemble your project.

In the ConfigureServices method, below the SwaggerDoc line, add

C#
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
c.IncludeXmlComments(filePath);

Changing "MyApi.xml" to the filename of your generated XML documentation defined in the project properties.

You must add documentation to your API endpoints by adding the necessary annotations to your C# code. These annotations are defined using XML comments and can be placed just above the method or class declaration.

For example, to document a GET endpoint that returns a list of users, use the annotation:

C#
/// <summary>
/// Retrieves a user by their ID.
/// </summary>
/// <param name="id">User id to get</param>
/// <returns>Returns IUser model</returns>
[HttpGet]
[Route("users/{id}")]
public IActionResult GetUser(int id)
{
// Implementation code here
}

By simply adding annotations to your code, Swagger can do the heavy lifting of generating comprehensive API documentation. This includes details about each endpoint, its parameters, and expected responses. This automated documentation is accessible via the Swagger UI, providing a user-friendly interface for exploring and interacting with your API.

Testing and Validating API Endpoints Using Swagger UI

Beyond generating API documentation, Swagger also offers powerful means of testing and validating your API endpoints. You can fire calls to your API and look at the answers through Swagger UI - so it's helpful when you're debugging and looking for confirmations on the correctness of your API implementation.

Proceed to your API Documentation Swagger UI page and start testing your API endpoints using the available interface to explore the different endpoints and make requests.

Imagine you have some POST endpoint to create a new user, for example. In the Swagger UI, a form with an input field is required for each of the method's parameters. You can fill in the needed parameters and click "Try it out!". Swagger UI will send the request to your API and show you the result so you can make sure this endpoint works.

As great as Swagger's interactive documentation interface is, writing automated tests for your API is still very important. These should be written in a testing framework such as xUnit, NUnit, or MSTest and include tests that account for scenarios and edge cases that may arise; this rigorous testing, in turn, makes sure your API will work reliably and as expected.

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

New comments for this post are currently closed.