Introduction

Swagger is a popular tool for designing, building, and documenting REST APIs. It also provides a built-in interface for testing APIs. However, in C#, we can programmatically test these endpoints using tools like HttpClient or frameworks like RestSharp. This article will guide you through testing an API endpoint using C# in conjunction with Swagger.

If you want to test API endpoints directly using Swagger, here are the detailed steps. Swagger provides an interactive UI (Swagger UI) that allows you to test API endpoints without needing additional tools.

Suppose I have written the following code in my project to get a response from an API mentioned in the code. For automated testing, you can use the HttpClient class in C#.

Code Example: Testing a GET Endpoint

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Base URL of the API
        string baseUrl = "https://api.example.com";
        
        // Endpoint to test
        string endpoint = "/api/v1/products";

        // Create HttpClient
        using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUrl) };

        try
        {
            // Send GET request
            HttpResponseMessage response = await client.GetAsync(endpoint);

            // Ensure the response is successful
            response.EnsureSuccessStatusCode();

            // Read and print the response content
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Response Content:");
            Console.WriteLine(content);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Request error: {e.Message}");
        }
    }
}

Now, let's check this API testing in Swagger. Here are the steps.

Step 1. Access Swagger UI

Replace the base URL with your base URL.

http://<base_url>/swagger

Step 2. Locate the Endpoint.

Step 3. Click on the Endpoint.

Step 4. Try the Endpoint.

Step 5. Execute the Request.

Advantages of Using Swagger with C#

Conclusion

By combining Swagger and C#, you can efficiently test and verify API functionality while automating workflows for repetitive tasks.