Creating proxy classes using AutoRest in .NET Core

Usually, with SOAP-based web services, we can easily generate client proxy classes by adding a service reference through Visual Studio. Whereas, with Web APIs, we use HttpClient class to do GET, POST, or any other operation on Web API, and write a few lines of code to set the request header, request body, other parameters, and serialize the response received from the server.

On the other hand, if our Web APIs are Swagger-enabled, we can easily generate client proxy classes using some third-party tools and libraries, where AutoRest is one of them. With AutoRest, we can generate client proxy classes by executing one single command through a command-line interface.

To start with, add a NuGet package, AutoRest, in your application which is going to access a Web API. Once the NuGet package is added, we can go to the user's directory and run autorest:

C:Users{username}.nugetpackagesAutoRest.17.3	ools

To generate the client code, we can run the following command:

C:Users{username}.nugetpackagesAutoRest.17.3	oolsautorest -Input http://{webapiname}.azurewebsites.net/swagger/v1/swagger.json -OutputDirectory Api

In the above command, Api is the output folder where the proxy classes will be generated, and it can be further used to consume Web API. Here is the sample snapshot of the folder generated:

This is the sample code to access Web API:

    public static void Main(string[] args) 
{
HelloWorldSwaggerAPI api = new HelloWorldSwaggerAPI();
api.ApiValuesByIdGet(1);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.62.168