ReSTful Web APIs- Is it that easy?

databaseprogrammingtutorialtutorial

Written by:

Reading Time: 4 minutes

Part I

ReSTful Web APIs is actually very easy to do. Initially it may look like a huge mountain, but by the time we finish, it will seem like an ant hill. I am by no means an expert on the subject, so feel free to  contribute in the comment section below.

Terminologies

First of all, what is the deal with all of these acronyms?

ReST: It stands for Representational State Transfer.

API: It stands for Application Programming Interface. It is kind of like a set of functions and library classes that enable you do stuff within a programming language. APIs I am referring to here are more like web services.

Together, ReSTful Web APIs also called ReSTful web services.

Another fancy acronyms out there on this subject is

ROA: ReST Oriented Architecture. That is SOA (Service Oriented Architecture) using ReST services

Components of a ReST architecture

Resources:

Resources are identified in requests and are separate from the representations. They are sources of specific information.

A web of resources: a single resource should not have so many details instead it should have links to or ways of referencing additional information.

Parts of a resource:

  1. The URI.

For example http://agbenu.com/resources/

  1. The Internet media type. That is MIME (Multipurpose Internet Mail Extension) type.

For example Content-Type: text/xml for  XML

Content-Type: application/json for JSON or otherwise.

  • The request method

This could be POST, GET, DELETE, or PUT.

Stateless:

Each connection is stateless. That is each new request should carry all the information needed to complete it and not rely on a prior interaction.

Cacheable:

Resources should have an expiration date and time.

Let me digress a little and give 2 points why I prefer ROA over SOAP based SOA.

  1. Easy to implement: If you have implemented SOAP, you will know what I mean. SOA has so many stuff when really all you might want to do, in some instances, is to read the value of an entity.
  2. Light weight approach: What is sent via HTTP requests is a relatively simply constructed query and not a huge bunch of XML stuff. Yeah, it’s really as light as a feather.

That is enough of the diversion.

There are 2 sides in the ReSTful Web API. And Einstein (yeah that’s you), before you go get any funny ideas, the 2 sides here are obviously the Server and the Client (since this is the web).

Let’s go into how they make calls to each other and what they are saying in these calls.

An Overview of the steps

 

  1. 1. Client constructs request as a URI.
  2. Send the request from the Client to the Server
  3. The Server will retrieve and parse the information
  4. The Server will generate the response
  5. The Server will send this response

Part II

URIs vs Resources

Consider the following

http://agenu.com/user/123

http://agenu.com/user

http://agenu.com/user/123 and   http://agenu.com/user are URIs

user and user/1 are the resource.

Resources are found within the URI.

Representation vs Resource

Think of it this way; the resource is the question whiles the representation is the answer based specifically on the question being asked. A representation is a set of attributes based on a resource.

http://agenu.com/user/123 will return a representation of the resource user/123

This could produce an output of

{“name”:  “Eli” , “city”: “Accra” }

There could be several formats of a representation.

Rules for naming resources

From what I read, as well as my own humble opinion, I feel these conventions are best:

Use the forward slash to show child objects, such as

*/users – show all users

*/ users /rights – show all rights

*/ users / rights /1 – show rights with id 1

The name and structure of URIs should convey meaning to your clients.

Part III

Request methods

  1. GET

This is used to retrieve data. That is for read only purposes. Do not use it to alter data, only to retrieve it.

For example

*/users  : list all users

*/ users/1 : list info for user with ID 1

 

For multiple parameters, I have seen the GET request method being used with the parameters in the URL.

For example;

http:// www.agenu.com/ userDetails?fname=Eli&lname=Agbenu

It would recommend that when passing long parameters or binaries use the POST request method and include the parameters in the post body.

 

  1. POST

It is used to create.

For example

*/users : create a new user

In some situations it could be used for also updating and deleting.

 

  1. PUT

Used to update data.

for example

/users/1 : update user with ID 1

 

  1. DELETE

Used to delete data.

for example

/user/1 : delete user with ID 1

HTTP codes

Use HTTP codes for errors and displaying information.

This a brief list of HTTP status codes.

2xx – success codes

200 – OK

201 – Created

202 – Accepted

 

3xx – redirection codes

301 – moved permanently

304 – Not modified

 

4xx – client side error

400 = Bad request

401 = Unauthorized

402 = Payment required

403 = Forbidden

404 = Not found

 

5xx – Server side error

500 = Internal server error

501 = Not implemented

503 = Service unavailable

Part IV

Writing your API class file:

Remember to include functions  that do the following:

  • process the request
  • get request method
  • send response
  • get status code message

Generating the response

The Representation format of the information is usually JSON / XML. There are other formats like HTML,  RSS, serialized PHP, CSV and JSON.

It is common to have the server response as an XML but it is preferable to use JSON.

The 2 components of a ReST response are the body and the status code.

First let’s look at a basic xml response

<?xml version='1.0'  encoding='UTF-8'?>
<myXML>
<function>order</function>
<values>
<orderID>123</orderID>
<reference>ref</reference>
</values>
</myXML>

 

Another example of a ReST response

<?xml version='1.0' encoding='UTF-8' ?>
<messages>
<message>
<date_created>Mon May 15 2013</date_created>
<user>Eli</user>
<text>Checking stuff out</text>
</message>
<message>
<date_created>Wed June 12 2013</date_created>
<user>Le roi</user>
<text>Clearing stuff out</text>
</message>
</messages>

The code to produce this output should look something like:

$sql = ‘select * from users’; // list info 
$q = mysql_query($sql);

Switch($format){
Case ‘json’:
Header(‘Content-Tye: application/json; charset=UTF-8’);
If(count($q)){
Echo json_encode(array(‘data’=>$q));
}else{
Echo json_encode(array(‘data’=>’Nothing found’));
}
Break;
Case ‘xml’:
$sCode = ‘’;
If(count($q)){
While($a=mysql_fetch_array($q)){
$sCode = “ 
<unit>
<id>{$a[‘id’]}</id>
<name>{$a[‘name’]}</name>
</unit>
”;
}
}
Header(‘Content-Type:text-xml; charset=UTF-8’);
Echo “
<?xml version=’1.0’ encoding=’UTF-8’ ?>
<info>
{$sCode}
</info>
”;
}

Example: adding information to users


$sql = ‘select * from users’; // list info 
$q = mysql_query($sql);

Switch($format){
Case ‘json’:
Header(‘Content-Tye: application/json; charset=UTF-8’);
If(count($q)){
Echo json_encode(array(‘data’=>$q));
}else{
Echo json_encode(array(‘data’=>’Nothing found’));
}
Break;
Case ‘xml’:
$sCode = ‘’;
If(count($q)){
While($a=mysql_fetch_array($q)){
$sCode = “ 
<unit>
<id>{$a[‘id’]}</id>
<name>{$a[‘name’]}</name>
</unit>
”;
}
}
Header(‘Content-Type:text-xml; charset=UTF-8’);
Echo “
<?xml version=’1.0’ encoding=’UTF-8’ ?>
<info>
{$sCode}
</info>
”;
}

Example: add information to user

$aData = array(‘result’=>’Info added successfully’);
Switch($format){
Case ‘json’:
Header(‘Content-Type:application/json; charset=utf-8’);
Echo json_encode($aData);
Break;
Case ‘xml’:
Header(‘Content-Type:text/xml; charset=utf-8’);
Echo “
<?xml version=’1.0’  encoding=’utf-8’ ?>
<res>
{$aData[‘res’]}
</res>
”;
Break;
}

An example displaying results:

$sql = 'select * from users where id = $id ';
$q = mysql_query($sql);
if(mysql_num_row($q)>0){
$r = array();
while($a = mysql_fetch_array($q)){
$r[] = $a ; 
}
$this-> response($this->json($r),200);
}
$this->response('',204);

private function json($d){
if(is_array($d)){
return json_encode($d);
}    }

 

 

XML response can be interpreted by an XML parser

You can even let clients specify the ReST response with XML or json by doing something like

users.xml or  users.json

Other issues

If PUT or DELETE requests do not work in your Apache setup, put the following in the .htaccess file in your application web root folder

<Limit GET POST PUT DELETE>

Order deny, allow

allow from all

</Limit>

 

Now, that is a wrap. That was not so bad?

 

Share comments, re-share it to let us know how this explanation went down with you. As always, keep learning and cheers.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up