Easy REST APIs With AutoRest
Explore the open source tool, AutoRest, and see a use case scenario.
Join the DZone community and get the full member experience.
Join For Free“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.
With the emergence 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.
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.
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: Refinitiv 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 Refinitiv Data Platform (RDP). 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.
RDP 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 RDP 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 Refinitiv Data Platform services.
1. Go to http://api.refinitiv.com to download JSON Swagger files for the required web services
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:
xxxxxxxxxx
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
xxxxxxxxxx
autorest --input-file=auth_oauth2_mod.json --csharp --output folder=CSharp_auth_oauth2 --namespace=Refinitiv.RDP.AutoRest.Auth.OAuth2
The above command generates C# classes with the Refinitiv.RDP.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 Refinitiv Data Platform.
xxxxxxxxxx
using System;
using Microsoft.Rest;
using Refinitiv.RDP.AutoRest.Auth.OAuth2;
using Refinitiv.RDP.AutoRest.Auth.OAuth2.Models;
using Refinitiv.RDP.AutoRest.HistoricalPricing;
using AuthError = Refinitiv.RDP.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:
With generated classes, developers just implement less than a hundred lines 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
- “Evolution & Growth of APIs” API 101, IBM Developer, 15 Aug. 2017, https://developer.ibm.com/apiconnect/documentation/api-101/evolution-growth-apis/
- 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
- “History of APIs” API EVANGELIST, 20 Dec. 2012, https://apievangelist.com/2012/12/20/history-of-apis/
- Levin, Guy. “RESTful APIs Technologies Overview” Rest API, REST API Security, RestCase, 18 Nov. 2017, https://blog.restcase.com/restful-apis-technologies-overview/
- “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
- “AutoRest”, GitHub, https://github.com/Azure/autorest
- “What Is Swagger?” Swagger Specification, swagger.io, https://docs.swagger.io/spec.html
Further Reading
Opinions expressed by DZone contributors are their own.
Comments