Generating C# Client from Virto Commerce Swagger with NSwag

Are you looking to simplify your API integration process and enhance your development workflow? Look no further than NSwag, a powerful tool that generates C# client code from your Virto Commerce Swagger JSON file. In this guide, we’ll walk you through the process, providing some tips and best practices along the way.

Step 1. Install NSwag Studio

Start by downloading NSwag Studio from the official GitHub repository: NSwag Studio Releases. NSwag Studio is a user-friendly GUI tool that streamlines the code generation process.

Step 2. Load Swagger JSON

Launch Virto Commerce Platform:

  • Navigate to https://<your_domain>/docs to view the Swagger UI .
  • Select required module from drop-down menu.
  • Click https://<your_domain>/docs/VirtoCommerce.Catalog/swagger.json to view the Swagger specification for /VirtoCommerce.Catalog module.

Step 3. Open NSwag Studio

  • Launch NSwag Studio.
  • Open Documents section and select Net60
  • Enter the swagger.json file URL in the Swagger Specification URL text box.
  • Click the Create local Copy button to generate a JSON representation of your Swagger specification.

Step 4. Configure NSwag Studio

Once the Swagger JSON file is loaded, you’ll find yourself in the NSwag Studio interface. Pay attention to the following settings:

  • Output: NSwag Studio supports various code generators for different programming languages. Choose “CSharp Client” for generating a C# client.
  • CSharp Client Settings: Configure the client options such as the namespace, class name, and output file path.

Step 5. Generate Client Code

Click on the Generate Outputs button to initiate the code generation process. NSwag Studio will generate the C# client code based on the provided settings and the Swagger JSON file.

Copy the generated C# code into a file in the client project that will consume the API.

Step 6. Start consuming the Virto Commerce API

Here’s an example of how to call the generated CatalogModuleProductsClient from C# using token authorization:

// Replace with your actual Virto Commerce base URL
string baseUrl = https://<your_domain>";
string accessToken = "TODO:AccessToken";

using (HttpClient httpClient = new HttpClient())
{
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

      var client = new CatalogModuleProductsClient(baseUrl, httpClient);

      try
      {
            // Call a method on the generated client
            var product = await client.GetProductByIdAsync("38bdbc3d-13dd-4f6c-bf6d-e4817e4ef8ec", "Full");

            Console.WriteLine($"Product ID: {product.Id}, Name: {product.Name}");
      }
      catch (ApiException ex)
      {
            Console.WriteLine($"API Exception: {ex.Message}");
      }
}

And result:

Step 7. Request Password Token

Here’s an example of how to call request password token using Snippet IdentityModel.

      ...
      string username = "TODO:YourUserName";
      string password = "TODO:YourPassword";

      var response = await httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
      {
            Address = baseUrl + "/connect/token",
            Scope = "offline_access",
            UserName = username,
            Password = password
      });

      if (response.IsError) throw new Exception(response.Error);
      string accessToken = response.AccessToken;
      ...

Step 8. NSwag Command-Line Tool

NSwag provides a command-line tool called NSwag.exe. NSwag’s command-line tool allows you to generate C# client code from a Swagger JSON file directly from the console. This approach is handy when you want to automate client code generation as part of your build or deployment process.

Summary

Generating a C# client from your Virto Commerce Swagger JSON file using NSwag can greatly simplify API integration and boost your development efficiency. By following this step-by-step guide and adopting best practices, you’ll be on your way to seamless API integration in no time.

Have any questions or suggestions? Feel free to share your thoughts in the comments below. Happy coding!