Before moving forward, let’s learn what NSwag is.
What is NSwag?
NSwag is a Swagger/OpenAPI 2.0 and 3.0 toolchain for .NET, .NET Core, Web API, ASP.NET Core, TypeScript (jQuery, AngularJS, Angular 2+, Aurelia, KnockoutJS and more) and other platforms, written in C#. The Swagger specification uses JSON and JSON Schema to describe a RESTful Web API. The NSwag project provides tools to generate Swagger specifications from existing ASP.NET Web API controllers and client code from these Swagger specifications.
The definition is a reference from the below link: https://github.com/RSuter/NSwag
What is OpenAPI?
In short, OpenAPI is a project which looks at standardizing how REST APIs are described.
As an example, if you take WSDL which is SOAP-based, it has standards. When you create a .asmx service, its document is generated in the form of XML which tells how to access that service and what operation that service provides. The same way, OpenAPI Initiative (OAI) is trying to standardize the APIs.
Details about this: - https://www.openapis.org/about
Tools
- Visual Studio 2017 with ASP.NET Core 2.1
- AspNetCore package from NuGet
Topic
- Creating ASP.NET Core Application
- Adding NSwag.AspNetCore from NuGet
- Configuration of NSwag in the startup file
- Running Application
- Downloading Nswag Studio
- Swagger specification
- Adding Console app
- Using Generated Client to call Web API
- Making Change in a Startup project
- Run Application to access API using Generated Client
- NSwag example with ASP.NET Core via API Explorer
- Adding class to DemoClient2 to console project.
- Run Application to access API using generated client with ASP.NET Core via API Explorer
Creating Asp.net core Application
In this step, we are going to simply create an ASP.NET Core API application. Name it as “WebNSwag.Sample”. While creating it, we are going to choose ASP.NET Core 2.1 Framework.
Adding NSwag.AspNetCore from NuGet
In this step, we are going to add NSwag.AspNetCore package from NuGet package to generate the Swagger UI.
After adding the NSwag.AspNetCore package, the project structure will look something like the below image.
Next, we need to configure the NSwag Services and Middleware in Startup.cs file.
Configuration of NSwag Services and Middleware in the startup file
In this part, we are going to configure services first in ConfigureServices method by adding the AddSwaggerDocument method.
Code snippet of Startup.cs
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
-
- services.AddSwaggerDocument();
- }
After registering the service, next, let us add NSwag middleware in the Configure Method.
Adding UseSwagger and UseSwaggerUi3 Middleware to Configure Method.
Code Snippet of Startup.cs
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc();
-
-
- if (env.IsDevelopment())
- {
- app.UseSwagger();
- app.UseSwaggerUi3();
- }
- }
Now, we are going to save and run the application.
If you are thinking "we have not added any API, how will it generate documentation for it?", then let me tell you that we have default API created with the name ValuesController.
Let’s run this application to check it.
Running Application
After running the application, it will execute the values using API GET method, as shown below.
Now, to see the documentation part of API, we need to enter the keyword “swagger” to the URL, as shown below.
After entering the URL, you will see the documentation of all HTTP methods (GET, POST, PUT, DELETE) of the API. If you want to share documentation with another team of APIs, you just need to share this URL of Swagger; that’s it.
You can also customize it by adding a description to it.
After generating the Swagger document, now we are going to generate the client code for accessing this API.
For doing that, first, we are going to download NSwag Studio.
Downloading NSwag Studio
To generate the client code for accessing this API with C# console application, here is the link to download: - https://github.com/RSuter/NSwag/wiki/NSwagStudio
After downloading, just install it on your PC. Since Visual Studio does not have support for it, we are using the NSwag Studio to generate the Client Code. Below is the view of NSwag Studio which we have downloaded.
After you see the view of NSwag studio let’s start generating Client code. There are various ways you can do it; let’s first start with “Swagger Specification”
- Swagger Specification
- Net core via API Explorer
- .Net Assembly
- Json Schema
The first demo we are going to work with is “Swagger Specification”
Swagger Specification
In Swagger Specification part, we need to provide “swagger.json” file path which we get from “swagger UI” using that swagger.json file NSwag is going to generate Client code.
Sample path: - http://localhost:53846/swagger/v1/swagger.json
Next, we are going to provide the swagger.json file path to Swagger Specification URL in NSwag Studio, as shown below.
After entering path just click on Create Local copy button to get json from it. And in the below Swagger Specification Json text area, you will able to see json which is download.
Next step after getting json is to Generate outputs and generate files. We are first going to generate Csharp client, and for doing that we are going to choose “Csharp client” checkbox.
After clicking on Csharp Client you can see various settings which you can configure to generate client class. We are not going to make one change in this setting, we are just going to uncheck “Inject Http Client via Constructor (life cycle is managed by caller)” because we are not going to inject HTTP client while accessing it.
After unchecking the option, we are going to click on Generate Outputs button to generate client code.
As you click on Generate Output button it will generate Class as shown in the above snapshot.
Next, we are going to generate Files; before that we are going to set output path where we want this generated file to upload.
For doing that we need to choose Settings tab of Csharp client and then just scroll until the end of it. There you will find “Output file path” and set your output path ,and also you need to provide a name to the file which will be generated.
Next click on Generate files button and check the folder where you have set output file path.
Below is the folder where Client code file “DemoClient.cs” is generated via NSwag Studio.
Next after generating files we are going to create a console app where we are going to add this generated file “DemoClient.cs” and access values API.
Adding Console application
To the same solution, we are going to Add Console Application with Name “ConsoleNSwag”.
After adding project, next, we are going to add generated class “DemoClient” to this Solution.
After adding a reference, you will see some error in console application. For resolving it we need to add Newtonsoft.Json reference to console application.
Adding Newtonsoft.Json reference to console application from NuGet Package.
After adding missing reference, next we are going to call client in the Main program and test some get method to see if it's working fine.
Using Generated Client to call Web API.
Code Snippet of a Console application
- using System;
- using MyNamespace;
-
- namespace ConsoleNSwag
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Welcome to Nswag Generated Client");
-
-
-
- var testClient = new ValuesClient();
-
-
- var getresult = testClient.GetAsync(1).GetAwaiter().GetResult();
-
-
- var getAllresult = testClient.GetAllAsync().GetAwaiter().GetResult();
-
- }
- }
- }
Now we have both projects in the same solution and we want to run them at once, so then we need to make a small change in project startup.
Making changes in project startup
To set just right-click on a solution -- then click on properties, then you will see properties dialog.
In that dialog set your project startup to “Multiple startup projects” and then in actions for both projects set as “Start”.
After setting it now we are ready to call API using a client which we have generated.
Let’s test the application by running and debugging it.
Run Application to access API using Generated Client
Now in debug mode you can see the response which we got from calling API. For doing this complex thing we have not written a single line of code and it's working fine.
After competing generating client using Swagger Specification and consuming it, next, we are going to have a look at another way of generating client code using “ASP.Net core via API Explorer”.
NSwag example with ASP.Net core via API Explorer
Now we are going to try the second way of generating client code using ASP.Net core via API Explorer. For doing that we need to open our NSwag Studio again.
In this part, first, we are going to set the Project file path which is the .csproj path of the project (“WebNSwag”) which we have created.
After selecting project path, next, we are going to select CSharp client check box to generate code. And then we are going to uncheck “Inject Http Client via Constructor (life cycle is managed by the caller)”. Because we are not going to inject HTTP client in this demo.
Next, we are going to set the “Output file path” along with the name of the file which we want for the demo. I have named the file as “DemoClient2”.
After setting output file path and entering file name next click on Generate Outputs button to generate Csharp client code.
After generating client code just click on the Generate Files button to generate a file which will be available on an output file path which you have set.
View of Output folder where the file is Generated.
Wow, we have generated a client just from Project Reference of .csproj. Now, as we have done already, we can just add this file to console application and consume web API using client generated code.
Adding class to DemoClient2 to console project.
Note - You can see we have excluded the first class because the name of the class which is generated is the same; however, we can make changes in settings to generate unique names.
Using Generated Client from ASP.NET Core via API Explorer to call the Web API.
Code Snippet
- using System;
- using MyNamespace;
-
- namespace ConsoleNSwag
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Welcome to Nswag Generated Client");
-
-
-
- var testClient = new ValuesClient("http://localhost:53846");
-
-
- var getresult = testClient.GetAsync(1).GetAwaiter().GetResult();
-
-
- var getAllresult = testClient.GetAllAsync().GetAwaiter().GetResult();
-
- }
- }
- }
Now, to call an API using generate the client, we need to make a small change in the code. We need to pass base API URL via the constructor.
After making the changes, now let’s test the application by running and debugging it.
Run Application to access API using Generated Client
In the below snapshot, we have successfully called values API using generated client code using NSwag Studio.
Finally, in this article, we have learned how to use NSwag to generate a Swagger documentation and client code in simple steps.