DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building a Distributed Multi-Language Data Science System
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Testing REST Controller Methods With JUnit 5 [Video]

Trending

  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  1. DZone
  2. Data Engineering
  3. Big Data
  4. Easy REST APIs With AutoRest

Easy REST APIs With AutoRest

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

By 
Jirapongse Phuriphanvichai user avatar
Jirapongse Phuriphanvichai
·
Updated Jan. 14, 20 · Opinion
Likes (13)
Comment
Save
Tweet
Share
72.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

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.

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: 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.

 

Elektron Data Platform

 

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

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:

Java
 




xxxxxxxxxx
1


 
1
 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

Java
 




xxxxxxxxxx
1


 
1
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.

Java
 




xxxxxxxxxx
1
59


 
1
using System;
2
using Microsoft.Rest;
3
using Refinitiv.RDP.AutoRest.Auth.OAuth2;
4
using Refinitiv.RDP.AutoRest.Auth.OAuth2.Models;
5
using Refinitiv.RDP.AutoRest.HistoricalPricing;
6
using AuthError = Refinitiv.RDP.AutoRest.Auth.OAuth2.Models.Error;
7
namespace ConsoleApp1
8
{
9
    class Program
10
    {
11
        static void Main(string[] args)
12
        {
13
            EDSAuthentication eds = new EDSAuthentication();
14
            try
15
            {
16
                var response = eds.PostToken("password"
17
                    , "<username>"
18
                    , "<password>"
19
                    , null
20
                    , "trapi"
21
                    , null
22
                    , "<clientid>"
23
                    , "true");
24
if (response is Tokenresponse)
25
                {
26
                    Tokenresponse tokenResp = (Tokenresponse)response;
27
TimeSeriesHistoricalPricingWebService timeseries = new TimeSeriesHistoricalPricingWebService(
28
                        new TokenCredentials(tokenResp.AccessToken));
29
var timeseriesResponse = timeseries.GetViewsInterdaySummariesUniverse("IBM.N");
30
                    foreach(var point in timeseriesResponse)
31
                    {
32
                        //Print Headers
33
                        foreach(var header in point.Headers)
34
                        {
35
                            Console.Write($"{header.Name}\t");
36
                        }
37
                        Console.WriteLine();
38
                        //Print Data
39
                        foreach(var data in point.Data)
40
                        {
41
                            foreach(var field in data)
42
                                Console.Write($"{field.ToString()}\t");
43
                            Console.WriteLine();
44
                        }
45
                    }
46
                }
47
                else if (response is AuthError)
48
                {
49
                    AuthError tokenError = (AuthError)response;
50
                    Console.WriteLine(tokenError.ErrorProperty + ":" + tokenError.ErrorDescription);
51
                }
52
            }
53
            catch (HttpOperationException ex)
54
            {
55
                Console.WriteLine("Exception:" + ex.Response.ToString());
56
            }
57
        }
58
    }
59
}



The output is:

EDP Output

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

  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!

REST Web Protocols Data science

Opinions expressed by DZone contributors are their own.

Related

  • Building a Distributed Multi-Language Data Science System
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Testing REST Controller Methods With JUnit 5 [Video]

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!