How to Automatically Generate Clients for your REST API

Create client code in seconds for all popular languages, and save hours of repetitive manual labor.

Photo by Jon Cartagena on Unsplash

Notes for the Sample API

If you decide to use the sample API to follow along with this guide, there are a couple of additional things you’ll need:

  • By default, the API serves content on port 5000. You can change this in Properties/launchSettings.json if that port doesn’t work for you.
  • If you are using Visual Studio, everything should be good to go once you hit F5. If you’re using another editor, you may need to dotnet build and dotnet run it to work.

AutoRest

AutoRest is a tool created and maintained by Microsoft that generates clients for RESTful web services, taking an OpenAPI specification as its input.

npm install -g autorest
autorest --latest

Generating the Client

In the previous step, we’ve installed AutoRest. Next up is grabbing the OpenAPI specification from our API, and feeding it to the AutoRest code generator.

http://localhost:5000/swagger/v1/swagger.json

Copying the Specification

If you are using Windows, you can use the following PowerShell command to create the directory we’ll be writing our specification to, and grab it over HTTP:

New-Item -ItemType Directory -Force -Path ./docs/openapiiwr http://localhost:5000/swagger/v1/swagger.json -o ./docs/openapi/api-v1.json
mkdir ./docs/openapi
cd ./docs/openapi
wget http://localhost:5000/swagger/v1/swagger.json

Feeding the Specification to AutoRest

Now that we have a local copy of our specification, all that’s left is feeding it to AutoRest. AutoRest has a bunch of options, including a ton of language switches you can use to specify what language the client should be written in.

  • --java
  • --typescript
  • --go
autorest --input-file=./docs/openapi/api-v1.json --v3 --csharp --use-datetimeoffset=true --sync-methods=none --output-folder=./src/SampleApi.Client --namespace=SampleApi.Client
var client = new SampleAPI(new Uri("http://localhost:5000"));var weatherForecast = await client.GetAsync();

Conclusion

We’ve generated a web service client based on its OpenAPI specification using AutoRest in C#. Client generation can be fully automated and requires no manual work anymore.

Software Engineer writing about his daily software adventures, wherever they may lead.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store