Top Related Projects
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
📘 OpenAPI/Swagger-generated API Reference Documentation
Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.
API Blueprint
The OpenAPI Specification Repository
Quick Overview
NSwag is a powerful Swagger/OpenAPI toolchain for .NET and TypeScript. It generates API clients, server-side controllers, and documentation from Swagger specifications, ASP.NET Core web APIs, or other sources. NSwag helps streamline API development and consumption across different platforms and languages.
Pros
- Supports multiple languages and frameworks (C#, TypeScript, JavaScript)
- Offers both command-line tools and a user-friendly GUI
- Integrates well with ASP.NET Core and can generate Swagger specs from existing APIs
- Provides customization options for generated code
Cons
- Learning curve can be steep for advanced customizations
- Documentation could be more comprehensive for some features
- May require additional setup for certain scenarios (e.g., authentication)
- Generated code might need manual tweaking for complex APIs
Code Examples
- Generating a C# client from a Swagger specification:
var document = await OpenApiDocument.FromUrlAsync("https://api.example.com/swagger/v1/swagger.json");
var settings = new CSharpClientGeneratorSettings { ClassName = "MyApiClient" };
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
- Creating a Swagger specification from an ASP.NET Core controller:
var document = await OpenApiDocument.FromControllerTypesAsync(new[] { typeof(MyController) });
var json = document.ToJson();
- Generating TypeScript client code:
var document = await OpenApiDocument.FromUrlAsync("https://api.example.com/swagger/v1/swagger.json");
var settings = new TypeScriptClientGeneratorSettings { ClassName = "MyApiClient" };
var generator = new TypeScriptClientGenerator(document, settings);
var code = generator.GenerateFile();
Getting Started
To get started with NSwag, follow these steps:
-
Install NSwag via NuGet:
dotnet add package NSwag.AspNetCore
-
Add NSwag services to your ASP.NET Core application in
Program.cs
:builder.Services.AddSwaggerDocument();
-
Enable Swagger UI in your application:
app.UseOpenApi(); app.UseSwaggerUi3();
-
Run your application and navigate to
/swagger
to view the Swagger UI and generated documentation.
Competitor Comparisons
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
Pros of Swagger Codegen
- Supports a wider range of programming languages and frameworks
- Has a larger community and more extensive documentation
- Offers a command-line interface for easier integration into build processes
Cons of Swagger Codegen
- Generally slower code generation compared to NSwag
- Can be more complex to set up and configure
- Less tightly integrated with the .NET ecosystem
Code Comparison
Swagger Codegen (Java):
public class PetApi {
private ApiClient apiClient;
public PetApi() {
this(Configuration.getDefaultApiClient());
}
}
NSwag (C#):
public partial class PetClient
{
private string _baseUrl = "https://petstore.swagger.io/v2";
private HttpClient _httpClient;
private Lazy<JsonSerializerSettings> _settings;
}
Both tools generate client code based on OpenAPI specifications, but NSwag is more focused on .NET technologies, while Swagger Codegen offers broader language support. NSwag tends to produce more idiomatic C# code, while Swagger Codegen's output may require additional customization for optimal integration with .NET projects. Swagger Codegen's wider language support makes it a better choice for multi-language environments, whereas NSwag excels in .NET-centric development scenarios.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Pros of openapi-generator
- Supports a wider range of programming languages and frameworks
- More frequent updates and active community contributions
- Offers more customization options for generated code
Cons of openapi-generator
- Steeper learning curve due to its extensive features
- Can be slower in code generation compared to NSwag
- May require more configuration for optimal results
Code Comparison
NSwag:
var document = await OpenApiDocument.FromUrlAsync("https://api.example.com/swagger/v1/swagger.json");
var settings = new CSharpClientGeneratorSettings { ... };
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
openapi-generator:
openapi-generator generate -i https://api.example.com/swagger/v1/swagger.json -g csharp -o ./output
Summary
Both NSwag and openapi-generator are powerful tools for generating API clients and server stubs. NSwag excels in .NET ecosystems with its seamless integration and ease of use, while openapi-generator offers broader language support and more customization options. The choice between them depends on your specific project requirements, target languages, and desired level of control over the generated code.
📘 OpenAPI/Swagger-generated API Reference Documentation
Pros of Redoc
- Focused on creating beautiful, customizable API documentation
- Supports themes and extensive styling options
- Offers a responsive, mobile-friendly design out of the box
Cons of Redoc
- Limited to OpenAPI/Swagger specification documentation
- Requires additional setup for server-side rendering
- Less integrated with code generation and API development workflows
Code Comparison
Redoc usage:
<!DOCTYPE html>
<html>
<head>
<title>API Documentation</title>
<meta charset="utf-8"/>
<script src="https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js"> </script>
</head>
<body>
<redoc spec-url="https://petstore.swagger.io/v2/swagger.json"></redoc>
</body>
</html>
NSwag usage:
var document = await OpenApiDocument.FromUrlAsync("https://petstore.swagger.io/v2/swagger.json");
var settings = new CSharpClientGeneratorSettings { ... };
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
NSwag offers a more comprehensive toolset for API development, including code generation and integration with .NET ecosystems. Redoc excels in creating visually appealing, user-friendly API documentation but is more limited in scope compared to NSwag's broader feature set.
Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.
Pros of Prism
- Language-agnostic API mocking and testing tool
- Supports multiple API specification formats (OpenAPI, Swagger, etc.)
- Provides a user-friendly CLI interface for easy integration
Cons of Prism
- Limited code generation capabilities compared to NSwag
- Less extensive documentation and community support
- Fewer language-specific features for .NET developers
Code Comparison
NSwag (C# client generation):
var document = await OpenApiDocument.FromUrlAsync("https://api.example.com/swagger/v1/swagger.json");
var settings = new CSharpClientGeneratorSettings { ... };
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
Prism (API mocking):
prism mock api.yaml
Summary
NSwag is a powerful tool for .NET developers, offering extensive code generation and integration capabilities. Prism, on the other hand, is a more versatile, language-agnostic solution for API mocking and testing. While NSwag excels in .NET-specific features and code generation, Prism provides a simpler approach to API simulation and validation across multiple platforms and languages.
API Blueprint
Pros of API Blueprint
- Language-agnostic design, allowing for broader adoption across different tech stacks
- Simpler, more human-readable syntax based on Markdown
- Strong focus on documentation and collaboration, making it easier for non-technical team members to contribute
Cons of API Blueprint
- Less comprehensive tooling ecosystem compared to NSwag
- Limited code generation capabilities, primarily focused on documentation
- Lacks built-in support for some advanced OpenAPI features
Code Comparison
API Blueprint:
# GET /users/{id}
+ Parameters
+ id: 1 (number, required) - User ID
+ Response 200 (application/json)
+ Attributes
+ name: John Doe (string)
+ email: john@example.com (string)
NSwag (C#):
[HttpGet("/users/{id}")]
public ActionResult<User> GetUser(int id)
{
// Implementation
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
API Blueprint focuses on a declarative, documentation-first approach, while NSwag leverages C# attributes for API definition, enabling tighter integration with .NET ecosystems and more robust code generation capabilities.
The OpenAPI Specification Repository
Pros of OpenAPI-Specification
- Industry-standard specification for describing RESTful APIs
- Extensive ecosystem of tools and libraries supporting the specification
- Language-agnostic, allowing for broader adoption across different platforms
Cons of OpenAPI-Specification
- Primarily focused on API description, not code generation
- Steeper learning curve for newcomers to API design
- Limited built-in tooling for implementation and testing
Code Comparison
OpenAPI-Specification (YAML):
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: List users
NSwag (C#):
[OpenApiTag("Users")]
[HttpGet("/users")]
public IActionResult GetUsers()
{
// Implementation
}
Key Differences
- OpenAPI-Specification is a standardized format for describing APIs, while NSwag is a toolset for .NET
- NSwag provides code generation capabilities, whereas OpenAPI-Specification focuses on API documentation
- OpenAPI-Specification is more widely adopted across different programming languages and platforms
- NSwag offers tighter integration with .NET ecosystems and frameworks
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
NSwag: The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript
NSwag | NJsonSchema | Apimundo | Namotion.Reflection
:point_right: Announcing Apimundo: An API documentation system based on NSwag and NJsonSchema :point_left:
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 OpenAPI/Swagger specification uses JSON and JSON Schema to describe a RESTful web API. The NSwag project provides tools to generate OpenAPI specifications from existing ASP.NET Web API controllers and client code from these OpenAPI specifications.
The project combines the functionality of Swashbuckle (OpenAPI/Swagger generation) and AutoRest (client generation) in one toolchain (these two libs are not needed). This way a lot of incompatibilites can be avoided and features which are not well described by the OpenAPI specification or JSON Schema are better supported (e.g. inheritance, enum and reference handling). The NSwag project heavily uses NJsonSchema for .NET for JSON Schema handling and C#/TypeScript class/interface generation.
The project is developed and maintained by Rico Suter and other contributors.
Features
- Generate Swagger 2.0 and OpenAPI 3.0 specifications from C# ASP.NET (Core) controllers
- Serve the specs via ASP.NET (Core) middleware, optionally with Swagger UI or ReDoc
- Generate C# or TypeScript clients/proxies from these specs
- Everything can be automated via CLI (distributed via NuGet tool or build target; or NPM)
- CLI configured via JSON file or NSwagStudio Windows UI
Ways to use the toolchain
- Simple to use Windows GUI, NSwagStudio
- By using the OpenAPI or OpenAPI UI OWIN and ASP.NET Core Middlewares (also serves the Swagger UI) (recommended)
- Via command line (Windows, Mac and Linux support through Mono or .NET Core console binary, also via NPM package)
- In your C# code, via NuGet
- In your MSBuild targets
- With ServiceProjectReference tags in your .csproj (preview)
- In your Azure V2 Functions (external project, might not use latest NSwag version)
Tutorials
- Add NSwag to your ASP.NET Core app
- Integrate the NSwag toolchain into your ASP.NET Web API project
- Generate an Angular TypeScript client from an existing ASP.NET Web API web assembly
- Video Tutorial: How to integrate NSwag into your ASP.NET Core Web API project (5 mins)
OpenAPI/Swagger Generators
- ASP.NET Web API assembly to OpenAPI (supports .NET Core)
- AspNetCoreOpenApiDocumentGenerator
- WebApiOpenApiDocumentGenerator
- Generates an OpenAPI specification for Web API controllers
- WebApiToOpenApiCommand
- Generates an OpenAPI specification for controllers in an external Web API assembly
- Also supports loading of .NET Core assemblies
- TypesToOpenApiCommand
- Generates an OpenAPI specification containing only types from .NET assemblies
Code Generators
- CSharp Client
- CSharpClientGenerator
- Generates C# clients from an OpenAPI specification
- Generates POCOs or classes implementing INotifyPropertyChanged supporting DTOs
- The generated clients can be used with full .NET, .NET Core, Xamarin and .NET Standard 1.4 in general
- CSharpClientGenerator
- CSharp Controllers (contract first/schema first development)
- CSharpControllerGenerator
- Generates Web API Controllers based on an OpenAPI specification (ASP.NET Web API and ASP.NET Core)
- CSharpControllerGenerator
- TypeScript Client
- TypeScriptClientGenerator
- Generates TypeScript clients from an OpenAPI specification
- Available templates/supported libraries:
- JQuery with Callbacks,
JQueryCallbacks
- JQuery with promises
JQueryPromises
- AngularJS using $http,
AngularJS
- Angular (v2+) using the http service,
Angular
- window.fetch API and ES6 promises,
Fetch
(use this template in your React/Redux app) - Aurelia using the HttpClient from aurelia-fetch-client,
Aurelia
(based on the Fetch template) Axios
(preview)
- JQuery with Callbacks,
- TypeScriptClientGenerator
Downloads
- Download latest NSwagStudio MSI installer (NSwagStudio.msi) (Windows Desktop application)
- Download latest NSwag command line tools and NSwagStudio (NSwag.zip)
NPM Packages
- NSwag: Command line tools (.NET and .NET Core) distributed as NPM package
NuGet Packages
Specification
- NSwag.Core
- The OpenAPI/Swagger reader and writer classes, see OpenApiDocument (.NET Standard 1.0 / 2.0 and .NET 4.5)
- NSwag.Core.Yaml (.NET Standard 1.3 / 2.0 and .NET 4.5)
- Extensions to read and write YAML OpenAPI specifications
- NSwag.Annotations (.NET Standard 1.0 / 2.0 and .NET 4.5)
- Attributes to decorate Web API controllers to control the OpenAPI generation
OpenAPI generation
- NSwag.Generation (.NET Standard 1.0 / 2.0 and .NET 4.5)
- Classes to generate OpenAPI specifications
- NSwag.Generation.WebApi (.NET Standard 1.0 / 2.0 and .NET 4.5)
- Classes to generate OpenAPI specifications from Web API controllers, see WebApiOpenApiDocumentGenerator
- NSwag.Generation.AspNetCore (.NET Standard 1.6 / 2.0 and .NET 4.5.1)
- (Experimental) Classes to generate OpenAPI specifications from ASP.NET Core MVC controllers using the ApiExplorer
Code generation
- NSwag.CodeGeneration (.NET Standard 1.3 / 2.0 / .NET 4.5.1)
- Base classes to generate clients from OpenAPI specifications
- NSwag.CodeGeneration.CSharp (.NET Standard 1.3 and .NET 4.5.1)
- Classes to generate C# clients from OpenAPI specifications, see CSharpClientGenerator and CSharpControllerGenerator
- NSwag.CodeGeneration.TypeScript (.NET Standard 1.3 and .NET 4.5.1)
- Classes to generate TypeScript clients from OpenAPI specifications, see TypeScriptClientGenerator
ASP.NET and ASP.NET Core
- NSwag.AspNetCore (.NET Standard 1.6 / 2.0 and .NET 4.5.1+)
- NSwag.AspNet.Owin (.NET 4.5+)
- ASP.NET Core/OWIN middlewares for serving OpenAPI specifications and Swagger UI
- NSwag.AspNet.WebApi (.NET 4.5+)
- ASP.NET Web API filter which serializes exceptions (JsonExceptionFilterAttribute)
Frontends
- NSwag.AssemblyLoader (.NET Standard 1.6 / 2.0 and .NET 4.5.1):
- Classes to load assemblies in an isolated AppDomain and generate OpenAPI specs from Web API controllers
- NSwag.Commands (.NET Standard 1.6 / 2.0 and .NET 4.5.1+):
- Commands for the command line tool implementations and UI
- NSwag.MSBuild (MSBuild .targets):
- Adds a .targets file to your Visual Studio project, so that you can run the NSwag command line tool in an MSBuild target, see MSBuild
- NSwag.ConsoleCore (.NET Core 1.0, 1.1, 2.0, 2.1 and 2.2):
- Command line tool for .NET Core (
dotnet nswag
) <DotNetCliToolReference Include="NSwag.ConsoleCore" Version="..." />
- Command line tool for .NET Core (
- NSwagStudio (Chocolatey, Windows):
- Package to install the NSwagStudio and command line tools via Chocolatey
CI NuGet Feed
https://www.myget.org/F/nswag/api/v3/index.json
The NuGet packages may require the Microsoft.NETCore.Portable.Compatibility package on .NET Core/UWP targets (if mscorlib is missing).
Usage in C#
To register the middlewares to generate an OpenAPI spec and render the UI, register NSwag in Startup.cs
:
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddOpenApiDocument(); // add OpenAPI v3 document
// services.AddSwaggerDocument(); // add Swagger v2 document
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseOpenApi(); // serve OpenAPI/Swagger documents
app.UseSwaggerUi(); // serve Swagger UI
app.UseReDoc(); // serve ReDoc UI
}
}
The following code shows how to read an OpenAPI/Swagger specification and generate C# client classes to call the described web services:
var document = await OpenApiDocument.FromFileAsync("openapi.json");
var clientSettings = new CSharpClientGeneratorSettings
{
ClassName = "MyClass",
CSharpGeneratorSettings =
{
Namespace = "MyNamespace"
}
};
var clientGenerator = new CSharpClientGenerator(document, clientSettings);
var code = clientGenerator.GenerateFile();
Check out the project Wiki for more information.
NSwagStudio
The generators can be used in a comfortable and simple Windows GUI called NSwagStudio:
Sponsors, support and consulting
Companies or individuals which paid a substantial amount for implementing, fixing issues, support or sponsoring are listed below. Thank you for supporting this project! You can also become a financial contributor:
Please contact Rico Suter for paid consulting and support.
Contributors
This project exists thanks to all the people who contribute. [Contribute].
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website.
Top sponsors:
Sponsors:
Backers
Thank you to all our backers!
Top Related Projects
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
📘 OpenAPI/Swagger-generated API Reference Documentation
Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.
API Blueprint
The OpenAPI Specification Repository
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot