Setting Up a .NET Core Web API with Swagger UI
Building a robust and well-documented API is a crucial aspect of modern software development. In this blog post, we'll walk you through the process of setting up a .NET Core Web API and integrating Swagger UI for easy API exploration and testing.
What is Swagger?
Swagger is an open-source framework that simplifies API development by allowing developers to describe, document, and test APIs. Swagger UI, in particular, provides a user-friendly interface for visualizing and interacting with your API endpoints.
Prerequisites
Before we get started, ensure you have the following prerequisites installed:
- .NET Core SDK
- Visual Studio Code (optional, but recommended)
- Swashbuckle.AspNetCore NuGet package
Step 1: Create a New .NET Core Web API Project
You can create a new .NET Core Web API project using the command-line or Visual Studio. We'll use the command-line for simplicity:
This command creates a new Web API project named MyWebApi
.
Step 2: Add Swagger to Your Project
To add Swagger to your project, you'll need to install the Swashbuckle.AspNetCore NuGet package. Open a terminal and navigate to your project's root directory, then run:
Step 3: Configure Swagger in Startup.cs
In your Startup.cs
file, locate the ConfigureServices method and add the Swagger generator:
Next, in the Configure
method, enable the Swagger UI:
Step 4: Create an API Controller
Create a sample API controller
to test Swagger. In your project, create a new file named SampleController.cs
:
Step 5: Build and Run Your Web API
Build your project by running:
And then run it:
Your API should now be running at https://localhost:5001
(or http://localhost:5000
).
Step 6: Explore Your API with Swagger
Open your web browser and navigate to https://localhost:5001/swagger (or http://localhost:5000/swagger). You'll be greeted with the Swagger UI interface, which allows you to explore and test your API endpoints interactively.
Conclusion
In this blog post, we've shown you how to set up a .NET Core Web API project and integrate Swagger UI for easy API documentation and testing. This combination will greatly simplify the process of developing and documenting your APIs, making it easier for both developers and consumers to work with your API. Happy coding!