Back to overview

An introduction to NSwag

By Karel Verhulst

.NET

Aug 2024

In the world of modern web development, API's play a crucial role in enabling communication between different software systems. The process of creating, documenting, and maintaining API’s can sometimes be a struggle. This is where the tool NSwag (together with NSwagStudio) comes into play, offering developers a streamlined way to work with OpenAPI specifications. There are other tools that can be of use, but for this blog we will focus on NSwag together with NSwagStudio.

Introduction

The reason why these tools are interesting is because of the fact that the customer is dealing with multiple projects that need to communicate with each other. Typically, this communication is managed using widely known NuGet packages. However, the challenge with this approach is that even small changes require multiple steps before they can be implemented in another project, which can be time-consuming.

I will demonstrate the capabilities of these tools and how they make our lives less painful, using a small application with code examples. The goal is to make two separate .NET solutions. An API solution and a client solution. Because I love creating games, I will work in this environment.

So, for the API solution we will have three methods where you can retrieve the following data:

  • All the game studios.

  • Detail information about a game studio with all the games.

  • Detail information about a game.

The client solution is designed for gamers who want to learn more about a game or a game studio. In this project there will only be a consumer that will use the APIs from the API solution. To demonstrate how easily we can use the different API endpoints in our client solution we will use NSwag and NSwagStudio. These tools will make sure that when updating the API endpoints in the solution, it will be easy to retrieve the updated endpoints with a simple click on a button.

NSwag - The Basics

NSwag is a project created by Rico Suter, Christoph Nienaber and Dave Brock. Because it is an open-source git project everyone can improve this project. The tool itself is an OpenAPI toolchain, which is a set of tools that are designed for describing API’s. It includes a set of various functionalities that can help the developer in documenting, generating code and managing APIs based on OpenAPI. It is important to mention that it can be used for projects in the .NET environment.

OpenAPI is a widely used standard for defining APIs, providing a comprehensive format to describe endpoints, request/response models, and authentication methods.

Install NSwag - how to use

In our API solution we are going to install NSwag in the API project, so that when we run the API, it will show in the browser a readable documentation view for the API endpoints.

The most common way to install NSwag into your .NET project is by using the Package Manager Console or the Manage NuGet Packages dialog. Depending on the .NET-implementation you can search for NSwag.AspNetCore, if you are building APIs with ASP.Net Core or use NSwag.AspNet.WebApi, when working on a legacy ASP.Net Web API project. In most modern applications, NSwag.AspNetCore is the right choice.

After the installation is complete, we add and configure the Swagger middleware inside the Program.cs file. First, we add the OpenApi to the service collection by adding the following code:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddOpenApiDocument();

Next, we want to enable the middleware by adding the following code, also in Program.cs:

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseOpenApi();
    app.UseSwaggerUI();
}

When we run the project, we can navigate to 2 URLs:

  •  http://localhost:<port>/swagger

  •  http://localhost:<port>/swagger/v1/swagger.json

The first one will show an overview of all your API's, ordered and sorted by name and action. It will also be possible to test your endpoints with your data. The second URL shows the Swagger specifications.

Now everything is set up and we have the API endpoints, in the client solution we can create a configuration file using the NSwagStudio tool and try to use the different API endpoints in the client.

NSwagStudio

NSwagStudio is a desktop application that provides a user-friendly interface for working with NSwag. It allows developers to interact with the NSwag toolchain without needing to use the command line. This GUI-based approach simplifies many tasks, especially for those who prefer visual tools over text-based configuration.

Install NSwagStudio - how to use.

To install the app, you can visit the NSwag GitHub page to download the latest version of NSwagStudio. Next you follow the installation steps and when everything is fine, you can open NSwagStudio.

After installing the tool, we will create a new .nswag file. This file will contain certain specifications/settings that you can change to let it work on your projects. In our client solution (presentation-layer) we create an NSwag-folder. Inside this folder we create two extra folders, one called Client (this will contain the .nswag file and some extra files that will be generated with the tool). The second folder will be called Facade, this will also contain a file that will be generated by the tool.

When we have a simple folder structure in the presentation-layer we can open NSwagStudio and create a new file (File > New). We give it a name and make sure to save it in the Client folder of our client solution. After that we edit that new .nswag file. Normally the basics are quite simple. First in the Input column, we set the Specification URL. This will be the URL path when running the API solution (http://localhost:<port>/swagger/v1/swagger.json)

Next, in the Outputs column we check the CSharp client’s checkbox, so that we can edit those settings. There are many settings to configure your client, but these are the most important ones:

  • Namespace and Class name;

  • Operation Generation mode;

  • Inject HttpClient via constructor;

  • Generate DTO types.

There are much more settings that you can edit, like primitive types, type of Json library and so one. Feel free to check them out and test the settings.

When you are happy with all the settings you can click on the “Generate Output” button. This will produce a complete C# client implementation. Then we can copy this code and create a file inside the Nswag > client folder in our second project to paste it.

We can make our lives a little bit easier by letting the tool create the file in our project. To do this, we go back to the Settings tab and at the bottom we have a section "Output" where we can choose the path where the file will be generated. The first file that we want to create automatically is the “Output” file, this path should be to the folder Nswag > Client. The other file is the “Contracts output” file, this path will be to the Nswag > Facade . After that the next step is clicking on the button "Generate Files".

A small remark: it can happen that there are certain packages missing, for example the Newtonsoft package. You can just install them using the package manager.

In our project, there will be a file that is generated by the tool. So now in our client solution we can use the ApiClient that was generated by NSwagStudio and use it as the controller where we want to use an API end point.

As the API controllers evolves with new endpoints being added, the next step is to run the API solution. Then open NSwagStudio, click the 'Generate Outputs' button, and the updates will automatically be reflected in the nswagAPIClient file (client solution), allowing for immediate use.

Conclusion  

NSwag and NSwagStudio are great tools for modern API development, offering you a blend of automation and user-friendliness.

Whether you are creating new API’s or working with existing ones, these tools can increase your workflow, allowing you to focus more on building great features and less on boilerplate code.

These tools offer you certain advantages such as consistency because they automatically generate client code with settings that you simply add to the tool. This way the risk of mismatches and errors is really small. It is also really efficient because for every new API you create; you can simply click on the button "Generate files" and it will update the client file. And finally, this tool is also really easy to use because of the visual interface.

If you haven’t yet explored NSwag and NSwagStudio, now is the time to enhance your API development process with these powerful tools.

Strong Under Pressure: resilient HTTP clients Thumb

By Michiel Mijnhardt

Nov 2024

Strong Under Pressure: resilient HTTP clients

Building resilient applications is crucial, and part of that resiliency is making sure your applications outgoing http requests are covered. The .NET go to ...

Injecting into an AutoMapper TypeConverter using AutoFac in .NET Framework 4.8 Thumb

By Ruben Verheyen

Jan 2024

Injecting into an AutoMapper TypeConverter using AutoFac in .NET Framework 4.8

Injecting dependencies into AutoMapper TypeConverters using Autofac in .NET Framework isn’t well-documented. After piecing together scattered resources, I ...

Application Logging – “That warm fuzzy blanket for when production doesn’t behave” Thumb

By Steven Hillaert

Nov 2023

Application Logging – “That warm fuzzy blanket for when production doesn’t behave”

Whenever I see a codebase that has logs, I feel safe. Because when things start to break, I know I’ll have data to help me fix it.

Cache primary btn default asset Cache primary btn hover asset Cache white btn default asset Cache white btn hover asset