Streamline Your API Development with NSwag
Generating clients for APIs can save you a significant amount of time and effort when building a project. With tools like NSwag, you can automate the process of creating client code, reducing the likelihood of errors and increasing productivity.
What is NSwag?
NSwag is a powerful tool that combines the functionality of Swashbuckle (OpenAPI/Swagger generation) and AutoRest (client generation) in one toolchain. It provides tools to generate OpenAPI specifications from existing ASP.NET Web API controllers and client code from these OpenAPI specifications.
Creating a.NET API with a Swagger Endpoint
To get started, let’s create a.NET API that exposes a Swagger endpoint. We’ll use the.NET SDK to create a new API project and add NSwag as a dependency. We’ll also create a TypeScript React app to consume our API later on.
Using NSwagStudio to Generate API Files
NSwagStudio is a visual tool that makes it easy to generate API code. We’ll use it to generate our API files and explore its features.
Programmatic API Generation with a.NET Console App
Sometimes, you may need more control over your API generation or want to do it as part of a CI/CD build process. In this case, we can create a.NET console app that generates typed clients programmatically.
Building a “Make a Client” Script
Let’s create a script that brings up the API, generates a client, and brings down the API. This script will use the start-server-and-test package to spin up our server-app and wait for the Swagger endpoint to start responding to requests.
Consuming the Generated API Client
Now, let’s consume our generated client from within our React app. We’ll run the script to generate the client, enable proxying from our client-app to our server-app, and use the autogenerated client to fetch data from the server.
A Note on NSwag Schemas
NSwag Schemas are JSON files that define the endpoints within our API and the data types they return. They’re essential for generating API code and using the Swagger API explorer.
The Future of API Development
With tools like NSwag, we can say goodbye to manual API code generation and hello to faster, more efficient development. By automating the process of creating client code, we can reduce errors and increase productivity.