How to generate API client library

In the previous article Getting started with Web API, we have created an API with Swagger. Swagger allows you to see the documentation of existing calls and provides an interface where they can be tested.

Moreover, a specification of a WebAPI can be used to generate a client library for different programming languages and frameworks, which is especially useful to safely share the types and caller methods for REST endpoints.

Generate client

When our API is up and running, we can start to generate one or more clients for different types of frameworks and programming languages.

1. Go to https://generator.swagger.io/#!/clients/generateClient

2. Navigate to clients controller and toggle /gen/clients/{language} POST operation. 

3. Click Try it out.

4. Select the language of the desired client library. I’ll go with csharp for C#.

5. Update request body with following JSON.

  • Specify package name for your API library project in packageName property.
  • Update URL set in swaggerUrl parameter to your own swagger documentation. It can be accessed by adding swagger/docs/{version} to your API url.
{     
  "options": { "packageName": "WebApi.Client" }, 
  "swaggerUrl": "http://mywebapi.azurewebsites.net/swagger/docs/v1"
}

6. Click Execute.

7 Parse linkproperty value from the response body and download archive with your client.

{   
  "code": "d40029be-eda6-4d62-b1ef-d05e2e91a72a",   
  "link": "http://generator.swagger.io:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a" 
}

8. Extract the archive and open its solution.

9. Build project.

Conclusion

Now, it’s up to you if you use .dll file or just reference the project in your application.

Hope it helps.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *