Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
APIs are essential in today's software development environment because they facilitate communication between various software systems and components. For developers to use APIs efficiently, there must be thorough and understandable documents. Two effective tools that can help the C# API documentation workflow are NSwag C# and IronPDF. This post will discuss how to use NSwag to generate API specifications with .NET Core and produce high-quality PDF documents from these specifications using IronPDF.
A .NET Swagger toolchain called NSwag was created to make it easier to create Swagger specifications, or OpenAPI documents, for APIs constructed using ASP.NET Web API, ASP.NET Core, or other .NET frameworks.
Controllers, models, and .NET assemblies can all be used by NSwag to automatically produce Swagger specs. NSwag generates comprehensive documentation that covers API endpoints, request/response forms, authentication techniques, and more by examining the structure of the API code.
Developers can easily include Swagger generation into their development processes by integrating NSwag with .NET projects. Developers can ensure that the documentation is updated with the codebase by adding NSwag to a .NET Core project, which will automatically produce Swagger specifications each time the project is built.
With the wide range of customization possibilities offered by NSwag, developers may easily adapt the generated Swagger specifications to meet their unique needs. Developers have control over many components of the generated documentation, including response codes, parameter explanations, and route naming conventions, through configuration settings and annotations.
The NSwag Base Class Library includes the core, Annotation, and code generation namespace, which should be available by installing from NuGet. To integrate NSwag into a C# application to generate code and Swagger specifications, and how NSwag may improve the efficiency of the development process.
Through automated client generation, developers can efficiently produce code for accessing APIs straight from within their desktop apps by integrating NSwag into a Windows desktop application. When developing desktop applications that communicate with online services or RESTful APIs, it can be quite helpful.
NSwag can be used in web applications to generate API documentation for internal APIs and client code for consuming external APIs. This aids developers in keeping their applications' frontend and backend components consistent.
Here is an example of code that shows you how to use NSwag to produce C# client code:
using NSwag.CodeGeneration.CSharp;
using NSwag;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CodeAnalysis;
class Program
{
static async Task Main(string[] args)
{
System.Net.WebClient wclient = new System.Net.WebClient();
// Create JSON file data from the Swagger net core web API
var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("http://localhost:5013/swagger/v1/swagger.json"));
wclient.Dispose();
var settings = new CSharpClientGeneratorSettings
{
ClassName = "Weather",
CSharpGeneratorSettings =
{
Namespace = "Demo"
}
};
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
var assembly = CompileCode(code);
var clientType = assembly.GetType("Demo.WeatherClient"); // Replace with your actual client class name
var httpClient = new HttpClient();
var client = (IApiClient)Activator.CreateInstance(clientType, httpClient);
var result = await client.GetWeatherForecastAsync();
foreach (var item in result)
{
Console.WriteLine($"Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}");
}
}
static Assembly CompileCode(string code)
{
using (var memoryStream = new MemoryStream())
{
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
List<MetadataReference> references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location));
references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "Microsoft.AspNetCore.Mvc.dll")));
references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Web.Http.dll")));
var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("ApiClient")
.AddReferences(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddSyntaxTrees(Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(code)).AddReferences(references);
var emitResult = compilation.Emit(memoryStream);
if (!emitResult.Success)
{
var diagnostics = emitResult.Diagnostics;
Console.WriteLine("Compilation errors:");
foreach (var diagnostic in diagnostics)
{
Console.WriteLine(diagnostic);
}
return null;
}
memoryStream.Seek(0, SeekOrigin.Begin);
return Assembly.Load(memoryStream.ToArray());
}
}
public interface IApiClient
{
Task<List<WeatherForecast>> GetWeatherForecastAsync(); // Replace with your actual method name and return type
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF { get; set; }
public string Summary { get; set; }
}
}
using NSwag.CodeGeneration.CSharp;
using NSwag;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CodeAnalysis;
class Program
{
static async Task Main(string[] args)
{
System.Net.WebClient wclient = new System.Net.WebClient();
// Create JSON file data from the Swagger net core web API
var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("http://localhost:5013/swagger/v1/swagger.json"));
wclient.Dispose();
var settings = new CSharpClientGeneratorSettings
{
ClassName = "Weather",
CSharpGeneratorSettings =
{
Namespace = "Demo"
}
};
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
var assembly = CompileCode(code);
var clientType = assembly.GetType("Demo.WeatherClient"); // Replace with your actual client class name
var httpClient = new HttpClient();
var client = (IApiClient)Activator.CreateInstance(clientType, httpClient);
var result = await client.GetWeatherForecastAsync();
foreach (var item in result)
{
Console.WriteLine($"Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}");
}
}
static Assembly CompileCode(string code)
{
using (var memoryStream = new MemoryStream())
{
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
List<MetadataReference> references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location));
references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "Microsoft.AspNetCore.Mvc.dll")));
references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Web.Http.dll")));
var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("ApiClient")
.AddReferences(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddSyntaxTrees(Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(code)).AddReferences(references);
var emitResult = compilation.Emit(memoryStream);
if (!emitResult.Success)
{
var diagnostics = emitResult.Diagnostics;
Console.WriteLine("Compilation errors:");
foreach (var diagnostic in diagnostics)
{
Console.WriteLine(diagnostic);
}
return null;
}
memoryStream.Seek(0, SeekOrigin.Begin);
return Assembly.Load(memoryStream.ToArray());
}
}
public interface IApiClient
{
Task<List<WeatherForecast>> GetWeatherForecastAsync(); // Replace with your actual method name and return type
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF { get; set; }
public string Summary { get; set; }
}
}
Imports NSwag.CodeGeneration.CSharp
Imports NSwag
Imports System.Reflection
Imports System.CodeDom.Compiler
Imports Microsoft.CodeAnalysis
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Dim wclient As New System.Net.WebClient()
' Create JSON file data from the Swagger net core web API
Dim document = Await OpenApiDocument.FromJsonAsync(wclient.DownloadString("http://localhost:5013/swagger/v1/swagger.json"))
wclient.Dispose()
Dim settings = New CSharpClientGeneratorSettings With {
.ClassName = "Weather",
.CSharpGeneratorSettings = { [Namespace] = "Demo" }
}
Dim generator = New CSharpClientGenerator(document, settings)
Dim code = generator.GenerateFile()
Dim assembly = CompileCode(code)
Dim clientType = assembly.GetType("Demo.WeatherClient") ' Replace with your actual client class name
Dim httpClient As New HttpClient()
Dim client = DirectCast(Activator.CreateInstance(clientType, httpClient), IApiClient)
Dim result = Await client.GetWeatherForecastAsync()
For Each item In result
Console.WriteLine($"Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}")
Next item
End Function
Private Shared Function CompileCode(ByVal code As String) As System.Reflection.Assembly
Using memoryStream As New MemoryStream()
Dim assemblyPath = Path.GetDirectoryName(GetType(Object).Assembly.Location)
Dim references As New List(Of MetadataReference)()
references.Add(MetadataReference.CreateFromFile(GetType(Object).GetTypeInfo().Assembly.Location))
references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "Microsoft.AspNetCore.Mvc.dll")))
references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Web.Http.dll")))
Dim compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("ApiClient").AddReferences(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(GetType(Object).Assembly.Location)).AddSyntaxTrees(Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(code)).AddReferences(references)
Dim emitResult = compilation.Emit(memoryStream)
If Not emitResult.Success Then
Dim diagnostics = emitResult.Diagnostics
Console.WriteLine("Compilation errors:")
For Each diagnostic In diagnostics
Console.WriteLine(diagnostic)
Next diagnostic
Return Nothing
End If
memoryStream.Seek(0, SeekOrigin.Begin)
Return System.Reflection.Assembly.Load(memoryStream.ToArray())
End Using
End Function
Public Interface IApiClient
Function GetWeatherForecastAsync() As Task(Of List(Of WeatherForecast)) ' Replace with your actual method name and return type
End Interface
Public Class WeatherForecast
Public Property [Date]() As DateTime
Public Property TemperatureC() As Integer
Public Property TemperatureF() As Integer
Public Property Summary() As String
End Class
End Class
For the API we wish to use, we specify the Swagger specification's URL (swaggerUrl
). Then the client code generated and executed into a DLL assembly is defined. OpenApiDocument
is employed. To load the Swagger document asynchronously from the given URL, use FromJsonAsync
. To alter the generated client code, we adjust the code generator's settings (CSharpClientGeneratorSettings
). In this example, the produced client code's class name and namespace are specified.
From the loaded Swagger document, we construct an instance of CSharpClientGenerator
and use it to produce the client code (client code). The created client code is saved to the designated output path. We respond to any exceptions or errors that may arise during the procedure, displaying the relevant notifications on the console.
NSwag can use a Swagger specification to generate client code in many languages, including Java, TypeScript, and C#. This makes it simple for developers to use APIs in their applications.
Using a Swagger specification as a basis, NSwag may also produce server code, such as ASP.NET Core controllers. This helps to scaffold server-side code for API implementations fast.
Given a Swagger specification, NSwag may produce interactive API documentation, such as Swagger UI. An interface that is easy to use is provided by this documentation for exploring and testing API endpoints.
To integrate with SOAP-based APIs, NSwag can produce proxy classes. This enables programmers to use produced client code to access SOAP services from within their applications.
NSwag is capable of verifying Swagger specifications to make sure they follow the OpenAPI/Swagger standard. This makes it easier to see any errors or discrepancies in the API documentation.
Developers can improve the workflow for API documentation by utilizing the advantages of both technologies by integrating NSwag with IronPDF. Developers can produce thorough, offline-ready .NET web API documentation that is readily available and shareable by using NSwag to generate Swagger specifications and IronPDF to transform them into PDFs. The following procedures are part of the integration process:
Install-Package IronPdf
For additional information regarding IronPDF's features, compatibility, and available downloads, visit the IronPDF page on NuGet.
Alternatively, you can incorporate IronPDF directly into your project by using its DLL file. To download the ZIP file containing the DLL, click the IronPDF download link. Unzip the file and add the DLL to your project.
To obtain the ZIP file containing the DLL, after unzipping, incorporate the DLL into your project.
By utilizing NSwag, Developers can create API documentation and client code for using APIs more quickly by using CodeGeneration.CSharp
in conjunction with IronPDF. The following steps are part of the integration workflow:
NSwag.CodeGeneration.CSharp
. The creation of client classes and methods for communicating with the API endpoints is automated in this step.CodeGeneration.CSharp
. In this stage, the request/response formats, authentication techniques, and API client endpoints are created into human-readable documentation.using IronPdf;
StringBuilder sb = new StringBuilder();
foreach (var item in result)
{
sb.Append($"<p>Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}</p>");
}
var Renderer = new IronPdf.HtmlToPdf();
var PDF = Renderer.RenderHtmlAsPdf(sb.ToString());
// Save PDF to file
PDF.SaveAs("output.pdf");
Console.WriteLine("PDF generated successfully!");
Console.ReadKey();
using IronPdf;
StringBuilder sb = new StringBuilder();
foreach (var item in result)
{
sb.Append($"<p>Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}</p>");
}
var Renderer = new IronPdf.HtmlToPdf();
var PDF = Renderer.RenderHtmlAsPdf(sb.ToString());
// Save PDF to file
PDF.SaveAs("output.pdf");
Console.WriteLine("PDF generated successfully!");
Console.ReadKey();
Imports IronPdf
Private sb As New StringBuilder()
For Each item In result
sb.Append($"<p>Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}</p>")
Next item
Dim Renderer = New IronPdf.HtmlToPdf()
Dim PDF = Renderer.RenderHtmlAsPdf(sb.ToString())
' Save PDF to file
PDF.SaveAs("output.pdf")
Console.WriteLine("PDF generated successfully!")
Console.ReadKey()
The code above accesses the retrieved data from the result object and appends the fields Date
, TemperatureF
, TemperatureC
, and Summary
to paragraphs in a loop. It then specifies the output file path for the PDF, then notifies the user that a PDF has been generated successfully.
Below is the result from the above code.
CodeGeneration
NSwag technologies like CSharp
and IronPDF work well together to streamline client code production and API documentation processes. Developers may speed up the creation of API-driven solutions, automate the creation of API documentation, and produce professional-looking PDF publications by integrating these tools into C# applications. NSwag.CodeGeneration.CSharp
with IronPDF offers developers a complete solution for efficiently documenting APIs and producing client code in C#, whether they are developing desktop, web, or cloud-based apps.
The $749 Lite bundle includes a perpetual license, one year of software maintenance, and an upgrade to the library. IronPDF offers free licensing with restrictions on redistribution and time. Users can assess the solution during the trial period without having to see a watermark. For additional information on the price and license, please see IronPDF's licensing information. Go to the Iron Software libraries page for additional information about Iron Software's product libraries.
9 .NET API products for your office documents