C Sharp - Annotation - OpenAPI - SwaggerTag

[SwaggerTag(“Product Retrieval”)]

What is the purpose of [SwaggerTag(“Product Retrieval”)]?
From Open AI on 3/27/2025

The [SwaggerTag()] attribute in .NET is part of the Swashbuckle package used for generating Swagger documentation for your API. Swagger (now known as OpenAPI) is a specification for describing and documenting RESTful APIs.
In the context of .NET and C#, the [SwaggerTag()] attribute is used to group or categorize related API endpoints under a specific tag in the Swagger UI documentation. It can make it easier for users of the API to navigate and understand its different sections by grouping related endpoints logically.

Purpose of [SwaggerTag()]:

  • Categorization: You can use the [SwaggerTag()] attribute to categorize your API methods (endpoints) into logical groups in the Swagger UI, making the documentation more organized.
  • Customization: You can specify a custom label or description for the tag, which will appear in the Swagger UI. This is helpful when you want to make your documentation more user-friendly or descriptive.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
[SwaggerTag("Product Retrieval")]
public IActionResult GetAllProducts()
{
// Your logic here
return Ok();
}

[HttpPost]
[SwaggerTag("Product Creation")]
public IActionResult CreateProduct([FromBody] Product product)
{
// Your logic here
return CreatedAtAction(nameof(GetAllProducts), new { id = product.Id }, product);
}
}

In the above example

  • The GetAllProducts method is tagged with “Product Retrieval”, and in the Swagger UI, it will be grouped under the “Product Retrieval” section.
  • The CreateProduct method is tagged with “Product Creation”, and it will appear under the “Product Creation” section.

Key Benefits:

  • Improves API Documentation: Users can easily understand the structure and functionality of the API.
  • Enhances Navigability: Tags help organize and provide context for each API endpoint.
  • Customizable: You can specify different labels to make the API documentation more descriptive.

If you’re using Swashbuckle for Swagger generation, make sure the necessary NuGet packages are installed and configured in your project. The [SwaggerTag()] attribute improves the documentation and provides a more structured API description.