Swagger to a .NET Core Web API project is a great way to document your API endpoints and allow developers to easily interact with your API. Here’s how you can add Swagger to your .NET Core Web API project:
- Install the necessary NuGet packages:
Microsoft.AspNetCore.Mvc.Versioning
Swashbuckle.AspNetCore
2. In the ConfigureServices
method of your Startup.cs
file, add the following code:
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(“v1”, new OpenApiInfo { Title = “My API”, Version = “v1” });
});
This code enables API versioning and adds Swagger to your project.
3. In the Configure
method of your Startup.cs
file, add the following code:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “My API V1”);
});
This code adds the Swagger UI to your project, which provides a user interface for interacting with your API.
4. Decorate your controller classes and methods with Swagger annotations to provide additional information about your API. For example:
[ApiController]
[Route(“api/[controller]”)]
[ApiVersion(“1.0”)]
[SwaggerTag(“Operations about Products”)]
public class ProductsController : ControllerBase
{
[HttpGet]
[SwaggerOperation(“GetAllProducts”)]
[SwaggerResponse(StatusCodes.Status200OK, “Success”, typeof(IEnumerable<Product>))]
[SwaggerResponse(StatusCodes.Status404NotFound, “Not Found”)]
public async Task<IActionResult> GetAllProducts()
{
// Code to get all products
}
}
In this example, the [SwaggerOperation]
annotation provides a friendly name for the operation, and the [SwaggerResponse]
annotations provide information about the possible responses to the operation.
5. Build and run your project, and navigate to /swagger
to view the Swagger UI and interact with your API.
now have Swagger integrated into your .NET Core Web API project.
“I would appreciate it if you could follow me, like my content, and share it with others.”
No comments:
Post a Comment