It’s highly recommended to make use of NSwag’s code generation capabilities. Choose one of the following options for code generation:
The main reason to use NSwag is the ability to not only introduce the Swagger UI and Swagger generator, but to make use of the flexible code generation capabilities. You don’t need an existing API—you can use third-party APIs that incorporate Swagger and let NSwag generate a client implementation. Either way, the development cycle is expedited and you can more easily adapt to API changes.
The NSwag NuGet package can be added with the following approaches:
From the Package Manager Console window:
From the Manage NuGet Packages dialog:
- Right-click your project in Solution Explorer > Manage NuGet Packages
- Set the Package source to “nuget.org”
- Enter “NSwag.AspNetCore” in the search box
- Select the “NSwag.AspNetCore” package from the Browse tab and click Install
Add and configure Swagger middleware
Import the following namespaces in the
using NSwag.AspNetCore; using System.Reflection; using NJsonSchema;
Startup.Configure method, enable the middleware for serving the generated Swagger specification and the Swagger UI:
public void Configure(IApplicationBuilder app) app.UseStaticFiles(); // Enable the Swagger UI middleware and the Swagger generator app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings => settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase; ); app.UseMvc();
Launch the app. Navigate to
/swagger to view the Swagger UI. Navigate to
/swagger/v1/swagger.json to view the Swagger specification.
NSwagStudiofrom the official GitHub repository.
Launch NSwagStudio. Enter the location of your swagger.json or copy it directly:
Indicate the desired client output type. Options include TypeScript Client, CSharp Client, or CSharp Web API Controller. Using a Web API Controller is basically a reverse generation. It uses a specification of a service to rebuild the service.
Click Generate Outputs.
Here you see a complete client implementation of the TodoApi.NSwag sample in C#:
- Put the file into a client project (for example, a Xamarin.Forms app). Start consuming the API:
var todoClient = new TodoClient(); // Gets all Todos from the Api var allTodos = await todoClient.GetAllAsync(); // Create a new TodoItem and save it in the Api var createdTodo = await todoClient.CreateAsync(new TodoItem); // Get a single Todo by Id var foundTodo = await todoClient.GetByIdAsync(1);
You can inject a base URL and/or a HTTP client into the API client. The best practice is to always reuse the HttpClient.
You can now start implementing your API into client projects easily.
Other ways to generate client code
You can generate the code in other ways, more suited to your workflow:
XML comments are enabled with the following approaches:
- Right-click the project in Solution Explorer and select Properties
- Check the XML documentation file box under the Output section of the Build tab:
NSwag uses Reflection, and the best practice for Web API actions is to return IActionResult. Consequently, NSwag can’t infer what your action is doing and what it returns. Consider the following example:
public IActionResult Create([FromBody] TodoItem item) if (item == null) return BadRequest(); _context.TodoItems.Add(item); _context.SaveChanges(); return CreatedAtRoute("GetTodo", new id = item.Id , item);
The preceding action returns
IActionResult, but inside the action it’s returning either CreatedAtRoute or BadRequest. Data annotations are used to tell clients which HTTP response this action is returning. Decorate the action with the following attributes:
[HttpPost] [ProducesResponseType(typeof(TodoItem), 201)] // Created [ProducesResponseType(typeof(TodoItem), 400)] // BadRequest public IActionResult Create([FromBody] TodoItem item)
The Swagger generator can now accurately describe this action, and generated clients know what they receive when calling the endpoint. Decorating all actions with these attributes is highly recommended. For guidelines on what HTTP responses your API actions should return, see the RFC 7231 specification.