Applicaton Development using RESTful APIs

20
Application Development using RESTful APIs Sourav Maji 4/7/14 Bachelor of Technology, 11/IT/35, Information Technology, National Institute of Technology, Durgapur

Transcript of Applicaton Development using RESTful APIs

Page 1: Applicaton Development using RESTful APIs

Application Development using RESTful APIs

Sourav Maji

4/7/14

Bachelor of Technology,

11/IT/35,

Information Technology,

National Institute of Technology,

Durgapur

Page 2: Applicaton Development using RESTful APIs

1 | P a g e

Acknowledgement

First I would like to thank Mr. Amit Bhagat, the co-founder of Surgerica, for giving me the opportunity of doing an internship within their organization. I would sincerely like to offer my special gratitude to Mr. Amarendra Kumar, the co-founder of Surgerica for constantly guiding me in the right direction whenever I went a bit astray. He has been a constant source of encouragement throughout the duration of my internship.

I also would like to thank all the employees who work at Surgerica. With their never ending patience and openness they created a very enjoyable working environment for me.

Lastly, I want to thank all the students, with whom I had joined as an intern at Surgerica. We experienced great things together and they have made the experience wonderful.

For me it was a unique experience to be in an actual working environment for the first time and to work on a very interesting project. It also helped me understand the various work responsibilities and the importance of meeting the project deadlines.

Page 3: Applicaton Development using RESTful APIs

2 | P a g e

Table of Contents

Sl. No. Topic Page No.

1. Acknowledgement 1

2. Significance of the project

Why are APIs important for any business?

3

3. Introduction 4

4. Google Maps API

My Project

Front End

Back End

5

6

8

5. WikiMedia API

My Project

Front End

Back End

10

11

13

6. SMS Achariya API

My Project

Front End

Back End

14

15

17

7. Conclusion 18

8. Reflection on the Internship 19

Page 4: Applicaton Development using RESTful APIs

3 | P a g e

Significance of the Project

Why are APIs important for any business?

“APIs make the modern Web what it is today.”

“APIs: building blocks for the future of digital marketing”

Application programming interfaces are helping marketing professionals cut through the digital

white noise. Understanding the world of Application Programming Interfaces (APIs) is one way for

agencies to stand out from the crowd whilst creating a unique experience for customers. Think of an

API as a plug - a simple and fast way to plug in and consume a service from a third-party provider.

Those services could be anything from content such as news, through to transactional services like

sending an email or SMS, making payments or placing a phone call. What's unique about APIs is now

one can consume these services through simple web interfaces that one’s software development

team can integrate in a matter of hours. Gone are the days of drawn out commercial negotiations,

the purchase and maintenance of third-party software and hardware, and time consuming,

expensive bespoke integrations. For these reasons APIs truly are a game changer.

Hurwitz & Associates

surveyed more than two

dozen leading edge

companies that are using

APIs to transform their

businesses. The results

were significant. The

research indicates that

companies that took

advantage of APIs

experienced benefits in

the following areas:

Significant Improvement in Partner/Customer Reach. There was a greater than 70%

increase in connecting to important customers and partners to build more profitable

relationships.

Increase in Web Traffic. There was 70% increase in web traffic and a 50% increase in web

service usage by customers once the Web API was implemented.

Faster Time to On-board Partners. Early adopters discovered that there was a 30% decrease

in the amount of time required to on-board partners. At the same time there was a 30%

increase in the ability to bring new innovative ideas to market quickly.

Page 5: Applicaton Development using RESTful APIs

4 | P a g e

Introduction

What are APIs?

An application-programming interface (API) is a set of programming instructions and standards for

accessing a Web-based software application or Web tool. A software company releases its API to the

public so that other software developers can design products that are powered by its services.

An API is a software-to-software interface, not a user interface. With APIs, applications talk to each

other without any user knowledge or intervention. As a user, one only sees one interface, but

behind the scenes, many applications are working together using APIs. This type of integration is

called seamless, since the user never notices when software functions are handed from one

application to another.

An API resembles Software as a Service (SaaS), since software developers don't have to start from

scratch every time they write a program. Instead of building one core application that tries to do

everything -- e-mail, billing, tracking, etc. -- the same application can contract out certain

responsibilities to remote software that does it better.

What are RESTful APIs?

The evolution of network protocols has led to the acceptance of a stack of agreed upon standards,

each addressing computer communication in a specific way. At the top of this stack are the

Application and Presentation layers, where business logic and the data resulting from it are

exchanged.

REST (REpresentational State Transfer) is a simple stateless architecture that generally runs over

HTTP. REST generally involves reading a designated Web page that contains an XML file. The XML file

describes and includes the desired content.

Some of the other technologies that are used are SOAP (Simple Object Access Protocol) approach,

which requires writing or using a provided server program (to serve data) and a client program (to

request data), JMS (which is specific to Java applications) and XML-RPC (which has many of the same

problems as SOAP without any of the benefits of standardization).

REST allows for a minimum amount of data to be passed using the same well-established

mechanisms that define the web without a lot of the encumbrances introduced by fatter protocols.

This allows programmers to more rapidly build programs that access and act upon data exposed via

APIs, even in environments with unreliable network speeds and limited computing power.

REST works almost exactly like a website in a browser. A resource is exposed to a program via a URL.

The program can access that URL and receive data about the resource, not unlike when you type in a

URL to your browser and get a web page back. Well-designed RESTful APIs include additional links

the program can follow to request related information - similar to how one would click on a link to

visit a new page - or to submit data to update the given resource - similar to how one would fill out a

web form to create a new account for a web site.

Page 6: Applicaton Development using RESTful APIs

5 | P a g e

Google Maps API

The Maps Engine API is a RESTful API. All requests to the API are

HTTP requests, so that any programming language with an HTTP

library can be used to query or modify data in the API. Resources are

represented as JavaScript Object Notation (JSON). JSON is a widely-

supported standard, with parsers available in most programming

languages.

Google maps API provides a wide assortment of services and contains more than 150 features, some

of which are:

o Drawing on the Map o Markers o Info Windows o Shapes o Symbols o Ground Overlays o Custom Overlays o Layers o Map Types o Services o Libraries

Page 7: Applicaton Development using RESTful APIs

6 | P a g e

MY PROJECT

I have created an Application where a user inputs his location, presses the submit button and is

taken to another page containing a list of hospitals, and their distances from the user. He is also

provided with a link which will display to him his travel directions on a map to any of the hospitals of

his choice.

Front End:

1. A user will find a Submit Panel asking the user to input his location. While typing his address, he

will also find a list of possible suggestions based on the letters he has typed. All suggested addresses

are limited to India. On completing the address he just has to click on the GET DISTANCE button

(refer to the picture below).

2. After clicking on the GET DISTANCE button, the user will be taken to a different page, displaying a

list of hospitals and their corresponding driving distances from them. The list also features a

NAVIGATE option to get the Driving directions to the hospital from the users location (refer to the

picture below).

Page 8: Applicaton Development using RESTful APIs

7 | P a g e

3. A map showing the destination Hospitals and the user’s origin is also displayed alongside the table

(refer to the picture below).

4. When the user clicks on the NAVIGATE link in the table, a map opens up in a popup window which

displays the Driving directions to the hospital of his choice (refer to the picture below).

Page 9: Applicaton Development using RESTful APIs

8 | P a g e

Back End:

1. In the initial Submit Panel, I have used the Google Places library to autocomplete the address field.

Below is a code snippet:

<script

src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">

</script>

<script type="text/javascript">

defaultBounds = new google.maps.LatLngBounds(

new google.maps.LatLng(8.06, 68.01),

new google.maps.LatLng(37.01, 97.25));

function autocompletef() {

var options = {

bounds: defaultBounds,

componentRestrictions: {country: 'in'}

};

Autocomplete = new

google.maps.places.Autocomplete((document.getElementById('origin')), options);

}

</script>

2. For the Distances table, I have used AJAX calls to fetch the latitudes and longitudes from the

database and then used Google’s Distance Matrix service to calculate the driving distances from the

user inputted location. Below is a code snippet:

<script type="text/javascript">

$(document).ready(function() {

$(':submit').on('click', function() {

$.ajax({

url: 'query.php',

data: 'button=' + $(this).val(),

dataType: 'json',

success: function(data) {

var destination = new Array();

var $_GET = [];

window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,

function(a, name, value) {

$_GET[name] = value;

});

var origin1 = ($_GET['origin']);

for (var i in data.id) {

Page 10: Applicaton Development using RESTful APIs

9 | P a g e

destination[i] = new google.maps.LatLng(data.lat[i], data.lon[i]);

}

var service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix(

{

origins: [origin1],

destinations: [destination[0], destination[1], destination[2],

destination[3], destination[4], destination[5], destination[6], destination[7]],

travelMode: google.maps.TravelMode.DRIVING,

unitSystem: google.maps.UnitSystem.METRIC,

avoidHighways: false,

avoidTolls: false

}, callback);

}

});

});

return false;

});

</script>

3. For displaying the Driving directions on the popup map, I have used Google’s Direction Service

API. Below is a code snippet:

var request = {

origin: start,

destination: end,

travelMode: google.maps.TravelMode.DRIVING

};

directionsService.route(request, function(response, status) {

if (status == google.maps.DirectionsStatus.OK) {

directionsDisplay.setDirections(response);

distanceInput.value = response.routes[0].legs[0].distance.value / 1000;

durationInput.value = response.routes[0].legs[0].duration.value / 3600;

origin.value = decodeURIComponent(org);

hosp.value = decodeURIComponent(hospital);

}

});

Page 11: Applicaton Development using RESTful APIs

10 | P a g e

WikiMedia API

The MediaWiki web service API (or WebAPI) provides convenient

access to wiki features, data and meta-data.

It provides direct, high-level access to the data contained in

MediaWiki databases.

A simple example:

This URL tells English Wikipedia's web service API to send us the content of the main page:

http://en.wikipedia.org/w/api.php?format=json&action=query&titles=Main%20Pa

ge&prop=revisions&rvprop=content

Using any programming language to make an HTTP GET request for that URL (or just visiting that link

in a browser) one will get a JSON document which includes the current wiki markup for the page

titled "Main Page". Changing format to jsonfm will return a "pretty-printed" HTML result good for

debugging.

Page 12: Applicaton Development using RESTful APIs

11 | P a g e

MY PROJECT

I have used the Wikipedia API to fetch wiki data relating to different illnesses, health conditions and

surgeries into a webpage of our own.

Front End:

1. A user will find a table listing a number of surgeries and illnesses and a corresponding “Go” link

(refer to the picture below).

2. Clicking on the link will take the user to a page displaying a short description of the illness with a

“View More” link at the end (refer to the picture below).

Page 13: Applicaton Development using RESTful APIs

12 | P a g e

3. Clicking on “View More” will take the user to a more detailed page about the same illness or

surgical procedure (refer to the picture below).

Page 14: Applicaton Development using RESTful APIs

13 | P a g e

Back End:

I have created a database containing a list of health conditions and surgery procedures, along with

their corresponding pages in Wikipedia. The list of surgeries is displayed to the user in an HTML

table. The link passes a GET variable containing the selected Wikipedia page title to a WikiDemo

page on our server. The page processes the GET variable and invokes the Wikipedia API by making

an API call. A code snippet is given below:

<script> var $_GET = [];

window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(a, name, value) { $_GET[name] = value; }); var page = ($_GET['pages']);

$.getJSON('http://en.wikipedia.org/w/api.php?format=json&action=parse&page=' + page + '&section=0&callback=?&prop=text', function(json) {

$('#wikiInfo').html(json.parse.text['*']); $("#wikiInfo").find("a:not(.references a)").attr("href", function() {

return "http://www.wikipedia.org" + $(this).attr("href"); }); $("#wikiInfo").find("a").attr("target", "_blank"); }); </script>

The $.getJSON method makes an HTML GET request to the Wikipedia API and receives the required

data in JSON format. It then parses the data using json.parse.text[‘*’] function and displays the

content in the div element ‘wikiInfo’.

Page 15: Applicaton Development using RESTful APIs

14 | P a g e

SMS Achariya API

API codes can be easily integrated to any web or

software application. The robust & stable HTTP API

is Compatible with all Programming Languages & Operating Systems. The XML API is designed to

send huge messages through a single push.

The API works on GET and POST METHOD, and the url to be used is http://yourdomain/api/sms.php

For every successful execution of the API call, the system generates a 'Response' which one can save

for tracking the operation. For multiple requests, the system response will consist of unique numeric

ids or other forms of responses, separated by comma.

Four different types of messages can be sent using the SMS Achariya API: Normal route, Priority

route, Marketing route, Transactional route.

Page 16: Applicaton Development using RESTful APIs

15 | P a g e

MY PROJECT

In my Project Application, I have made an SMS Gateway for Transactional SMSs which support DND

templates. Moreover the content of the messages is dynamic, i.e. although the messages follow a

basic template the information carried by them has to be dynamically fed to them at the time of

sending.

Front End:

1. A user will be presented a list of customers and asked to select one to send an SMS. There are also

options on this page to add new customer details, view previous message logs, and a search field to

search for any customer using his mobile number.

2. After clicking on the Send SMS button the user will be taken to another page, asking him to select

one of the many previously approved DND templates.

Page 17: Applicaton Development using RESTful APIs

16 | P a g e

3. After selecting the desired template, the user now needs to fill in the dynamic values.

4. The complete message with the typed in values is displayed to the user. If he is not satisfied he

can go back to the previous page to fill the values again, or if he is happy, he can proceed to send the

SMS.

5. This final page reports whether a message has been sent or not. If the SMS was not sent, the

reason for the error is displayed otherwise the message is stored in the database along with the

message id and time for future referrals.

Page 18: Applicaton Development using RESTful APIs

17 | P a g e

Back End:

The whole application is built using PHP. Unauthorised use of the SMS Gateway is restricted by the

use of Sessions. The different values are passed from one page to another using HTTP GET and POST

methods. The final message is sent by hitting the SMS Achariya API with a url containing the

message and other various parameters. This is done using cURL function in PHP. Here is the code

snippet:

$message = urlencode($message);

$parameters =

"uid=$uid&pin=$pin&sender=$sender&route=$route&tempid=2&mobile=$mobile&messa

ge=$message";

$url = "http://$domain/api/sms.php";

$ch = curl_init($url);

if ($method == "POST") {

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);

} else {

$get_url = $url . "?" . $parameters;

curl_setopt($ch, CURLOPT_POST, 0);

curl_setopt($ch, CURLOPT_URL, $get_url);

}

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$return_val = curl_exec($ch);

Page 19: Applicaton Development using RESTful APIs

18 | P a g e

Conclusion

What is the future of APIs?

APIs are about to enter a new phase, one where developers can easily program using multiple APIs

at once, and non-developers can easily introduce API automation into both their business and

personal worlds. A time where APIs are seen as a valuable resource anyone can quickly put use, not

just as a technical interface only high-end developers understand.

Web APIs have matured out of its earlier service oriented architecture (SOA) roots, often shedding a

rigid SOAP approach to a more flexible RESTful implementation, increased efficiency by opting for

more lightweight JSON over bloated XML, and becoming more accessible with API explorers and

interactive documentation.

Now with over 6,000 public APIs available, there is a need to get more efficient about how we work

with APIs, and evolve to where we can truly program the web. But to get there, we have to add a

new platform layer that can help standardize the authentication, interfaces and resource types

available--simplifying how not just developers, but average users can take advantage of APIs.

One approach is targeting developers with new languages, or extensions of existing languages that

can be used to program against one or many APIs. The second approach is targeting a wider

audience with automation platforms that create API driven tasks. Both approaches provide a much

needed platform to help make APIs more accessible, where one is still targeting the developer

community and the other will allow anyone to take advantage of APIs through special automation

tools and connectors.

The beauty of an API is that pretty much any kind of implementation is possible. The API is the

ingredient, and the recipe is only constrained by the imagination of the developer.

Page 20: Applicaton Development using RESTful APIs

19 | P a g e

Reflection on the Internship

Regarding my learning goals I shortly discuss my experiences; if I have achieved my goal, whether I experienced difficulties and what I think I have to improve.

Learning goals

The functioning and working conditions of an organization: At the beginning, I did not have any experience of working in any organisation, but with time I learned the importance of meeting project deadlines and working under an authority.

Enhancing communication skills: My stay has contributed to my communication skills, and I would like to sharpen it even more in the future. To contribute more to projects and to progress faster, I

want to learn to make a more confident impression and to express my ideas and opinions more certain.

The use of skills and knowledge gained in college: A lot of the concepts I had learnt at college were mainly theoretical and lacked much practical application. The subject of Internet and Web Technology which was taught in the previous semester was really helpful in building the applications. I could finally put my academic knowledge to actual use.

Skills and knowledge that might be improved to work in a professional environment: During the internship, I have realised that a lot of technical knowhow is important and one should be completely updated about the technological advancements in order to work in a professional environment. I also figured out that prior planning is vital for projects to be completed within a stipulated amount of time.

Learning new Skills: I was introduced to the wonderful world of APIs and loved programming with them. I learned that APIs are indeed very important in today’s scenario where Applications can interact with one another without human intervention. A lot of large web services have their own APIs and it has grown a curiosity within me to explore new ones.