Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Easy REST APIs With AutoRest

DZone 's Guide to

Easy REST APIs With AutoRest

Explore the open source tool, AutoRest, and see a use case scenario.

Free Resource

Dog taking a REST

It's easy to REST with AutoRest.

“We live in an API-driven world,” said Julia Kreger, OpenStack Ironic project team lead and principal software engineer at Red Hat.

API is an acronym for “Application Programming Interface.” It has a long history since the first computer programs were written. At first, APIs form “contracts” for accessing resources from the operating system, software libraries, or other systems.

You may also like: 


With the emerge of the internet and HTTP, the Web API was introduced. It uses a request and response mechanism to access services or resources available on other servers. According to the information from www.programmableweb.com, the total number of Web APIs has dramatically increased since 2005. In June 2019, there were more than 22,000 Web APIs in their directory.

Growth in Web APIs since 2005

Nowadays, various kinds of data are available through web APIs, such as maps, weather, social, and financial information. This demonstrates that many companies eventually admit that web APIs are essential to their businesses.

The most popular technology for web APIs is Representation State Transfer (REST). It is simple and easy to use because it is based on the HTTP protocol, which is commonly used to view regular web pages. However, data scientists or developers who are not familiar with the HTTP protocol may encounter some obstacles when developing applications to use REST APIs.

Fortunately, with the help of code generation tools like AutoRest, anyone can easily develop applications that consume data from REST APIs.

AutoRest

AutoRest is an OpenAPI (Swagger) specification code generator. It is a Node.js open-source tool used to generate client libraries for accessing RESTful web APIs. It can generate libraries for many programming languages including CSharp, Node.js, Python, Java, Ruby, Go, PHP, and TypeScript.

Programming Languages

In short, AutoRest can generate the code accessing the Web APIs from Swagger files. Swagger files use the OpenAPI specification to describe the structure of the Web APIs so that machines or applications can understand their structure and usage. Swagger files are available in both JSON (JavaScript Object Notation) and YAML (YAML Ain’t Markup Language) formats.

Use Case Scenario: Elektron Data Platform

In this section, I will demonstrate how to use AutoRest to generate C# libraries in the real use case scenario. 

To do this, I will use as an example a cloud-based product from Refinitiv called Elektron Data Platform (EDP). This product provides financial data and associated analytics that’s used by financial professionals globally. This data includes real-time data from various stock exchanges around the world as well as reference and historical data.

Elektron Data Platform

EDP includes simple standard REST-based APIs for accessing this financial data. The requested data is delivered using a Request-Response mechanism. An application uses a web request (HTTP GET, POST, PUT or DELETE) to convey the request message and parameters, and the EDP service responds with data synchronously.

Developers can download a swagger file for each API. With this file, AutoRest can be used to generate client libraries for accessing RESTful web services.

There are three steps to use AutoRest to generate client libraries for Elektron Data Platform services.

1. Go to http://api.refinitiv.com to download JSON Swagger files for the required web services

api.refinitiv.com

2. Run a Node.js script from GitHub to verify and add the required OperationId field in the JSON Swagger file. AutoRest uses the OperationId field to determine the method name for a given API

 node app.js --input auth_oauth2_beta1.json --output auth_oauth2_mod.json 

The script will create a new file auth_oauth2_mod.json, which contains the OperationId fields.

3. Run AutoRest with the modified JSON Swagger file to generate client libraries

 autorest --input-file=auth_oauth2_mod.json --csharp --output-folder=CSharp_auth_oauth2 --namespace=Refinitiv.EDP.AutoRest.Auth.OAuth2

The above command generates C# classes with the Refinitiv.EDP.AutoRest.Auth.OAuth2 namespace in the CSharp_auth folder.

The following code uses C# classes generated by AutoRest to retrieve time series pricing intraday summary data of IBM (International Business Machines Corp) traded in the New York Stock Exchange from Elektron Data Platform.

using System;
using Microsoft.Rest;
using Refinitiv.EDP.AutoRest.Auth.OAuth2;
using Refinitiv.EDP.AutoRest.Auth.OAuth2.Models;
using Refinitiv.EDP.AutoRest.HistoricalPricing;
using AuthError = Refinitiv.EDP.AutoRest.Auth.OAuth2.Models.Error;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            EDSAuthentication eds = new EDSAuthentication();
            try
            {
                var response = eds.PostToken("password"
                    , "<username>"
                    , "<password>"
                    , null
                    , "trapi"
                    , null
                    , "<clientid>"
                    , "true");
if (response is Tokenresponse)
                {
                    Tokenresponse tokenResp = (Tokenresponse)response;
TimeSeriesHistoricalPricingWebService timeseries = new TimeSeriesHistoricalPricingWebService(
                        new TokenCredentials(tokenResp.AccessToken));
var timeseriesResponse = timeseries.GetViewsInterdaySummariesUniverse("IBM.N");
                    foreach(var point in timeseriesResponse)
                    {
                        //Print Headers
                        foreach(var header in point.Headers)
                        {
                            Console.Write($"{header.Name}\t");
                        }
                        Console.WriteLine();
                        //Print Data
                        foreach(var data in point.Data)
                        {
                            foreach(var field in data)
                                Console.Write($"{field.ToString()}\t");
                            Console.WriteLine();
                        }
                    }
                }
                else if (response is AuthError)
                {
                    AuthError tokenError = (AuthError)response;
                    Console.WriteLine(tokenError.ErrorProperty + ":" + tokenError.ErrorDescription);
                }
            }
            catch (HttpOperationException ex)
            {
                Console.WriteLine("Exception:" + ex.Response.ToString());
            }
        }
    }
}

The output is:

EDP Output

With generated classes, developers just implement less than a hundred line of code to retrieve and display the data. However, if developers directly use the HTTP Client to retrieve and display data, it will use a lot more code than this. Therefore, using AutoRest can save developers a lot of time when implementing the application and allow developers to focus on the business logic instead of the HTTP protocol.

References

  1. “Evolution & Growth of APIs” API 101, IBM Developer, 15 Aug. 2017, https://developer.ibm.com/apiconnect/documentation/api-101/evolution-growth-apis/
  2. Santos, Wendell. “APIs show Faster Growth Rate in 2019 than Previous Years”, ProgrammableWeb, 17 Jul. 2019, https://www.programmableweb.com/news/apis-show-faster-growth-rate-2019-previous-years/research/2019/07/17
  3. “History of APIs” API EVANGELIST, 20 Dec. 2012, https://apievangelist.com/2012/12/20/history-of-apis/
  4. Levin, Guy. “RESTful APIs Technologies Overview” Rest API, REST API Security, RestCase, 18 Nov. 2017, https://blog.restcase.com/restful-apis-technologies-overview/
  5. “Ironic OpenStack Bare Metal Gains Momentum with Containerized Application Architectures” Open Infrastructure Summit, OpenStack, 29 Apr. 2019, https://www.openstack.org/news/view/423/ironic-openstack-bare-metal-gains-momentum-with-containerized-application-architectures
  6. “AutoRest”, GitHub, https://github.com/Azure/autorest
  7. “What Is Swagger?” Swagger Specification, swagger.io, https://docs.swagger.io/spec.html

Further Reading

Developing REST APIs

Be the BEST at Your REST API!

Topics:
swagger ,rest api ,c# ,integration ,tutorial ,autorest ,rest apis ,easy rest apis

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}