Friday, September 23, 2022

Generate C# client for API with Swagger (OpenAPI) support

If you develop web API it worth to consider to add support for Swagger specification (or OpenAPI specification) to it. As documentation says:

OAS defines an API’s contract, allowing all the API’s stakeholders, be it your development team, or your end consumers, to understand what the API does and interact with its various resources, without having to integrate it into their own application.

One of the practical advantage is possibility to easily create documentation for web API which supports Swagger. Another big advantage is possibility to generate SDK (client) for web API using preferred language. There are Swagger Codegen tools for that. One of them is online web service https://generator3.swagger.io/api/generate which can be used for generating SDK online.

Let's see how to use that and generate C# client for sample web API https://petstore.swagger.io/v2/swagger.json with Swagger support. We need to send HTTP POST request tohttps://generator3.swagger.io/api/generate with the following body:

{
  "specURL" : "https://petstore.swagger.io/v2/swagger.json",
  "lang" : "csharp",
  "type" : "CLIENT",
  "codegenVersion" : "V3"
}

and add header "Content-Type": "application/json". In "lang" parameter we specified which language should be used for generating SDK. After that web service will generate C# client for us and will return generated .cs classes in zip archive. If you use Postman then instead of Send button need to use Send and Download:


Zip archive will contain Visual Studio solution with generated SDK for web API:

As you can see it contains generated model classes and API for working with them so no need to code it manually. It may save a lot of time when you work with external web API.

Update 2023-03-29: see also another blog post Generate strongly-typed C# client for ASP.Net Core Web API with OpenAPI (swagger) support running on localhost which describes how to generate C# client for web api running on localhost.

No comments:

Post a Comment