There are multiple ways to generate a C# client based on an OpenAPI specification file. Today I want to show you how this can be done directly inside Visual Studio.
To import an OpenAPI reference, you can right-click on your project and choose Add –> Service Reference:
Choose OpenAPI from the list of possible service references and click on Next:
Now we can specify the details to our OpenAPI JSON file. Click on Finish to generate the client:
It can take some time to generate the client. So be patient.
What is happening behind the scenes?
Let us have a look at all the things that Visual Studio is doing behind the scenes.
First a copy of the OpenAPI json file is imported into our project and stored inside an OpenAPIs folder:
On this JSON file the build action is set to Open API File Reference and specific code generation attributes are configured:
Our updated csproj file looks like this:
<Project Sdk="Microsoft.NET.Sdk.Worker"> | |
<PropertyGroup> | |
<TargetFramework>net6.0</TargetFramework> | |
</PropertyGroup> | |
<ItemGroup> | |
<OpenApiReference Include="OpenAPIs\v1.json" CodeGenerator="NSwagCSharp" Namespace="GettingStarted" ClassName="CapakeyClient"> | |
<SourceUri>https://geo.api.vlaanderen.be/capakey/v2/swagger/docs/v1</SourceUri> | |
</OpenApiReference> | |
</ItemGroup> | |
</Project> |
Behind the scenes the code generator is using the Microsoft.dotnet-openapi command line tool which uses NSwag in the end.
We can further control what is generated by specifying additional options:
<ItemGroup> | |
<OpenApiReference Include="OpenAPIs\v1.json" CodeGenerator="NSwagCSharp" Namespace="GettingStarted" ClassName="CapakeyClient" Options="/JsonLibrary:SystemTextJson" > | |
<SourceUri>https://geo.api.vlaanderen.be/capakey/v2/swagger/docs/v1</SourceUri> | |
</OpenApiReference> | |
</ItemGroup> |