Search Google

Monday 16 February 2015

What is Web Services and Rest

Suppose I want to provide a search facility that visitors to my website can use. I could build my own search application from scratch, but that would be a lot of work, ranging from building a database of information to developing various indexing and hashing features. Instead, I can use the Google Search web service on my website. The web service accesses Google's info database in response to the visitor's search, and it returns the requested results to the visitor.
A web service consists of several methods that are advertised for use by the general public. To make it possible for every application to access a web service, these services use web service protocols, including REST, SOAP, JSON-RPC, JSON-WSP, XML-RPC, and so on. A web service can exchange data in any format, but two formats are the most popular for data exchange between applications:
  • XML. Standard format for data exchange among applications, in order to avoid datatype-mismatch problems.
  • JavaScript Object Notation (JSON). Text-based open standard for representing data. Uses characters such as brackets ([]), braces ({}), colons (:), and commas (,) to represent data.
In this article, we'll focus on the JSON data-exchange format. Data in JSON is represented using simple key/value pairs, with more-complex data represented as associative arrays. For example, strings in JSON representation look like this:

["bintu", "bmharwani@yahoo.com",...]
 
The information can also be represented in the form of key/value pairs:
{"name" : "bintu", "email": "bmharwani@yahoo.com"}
 
REST stands for Representational State Transfer. (It is sometimes spelled "ReST".)
 It relies on a stateless, client-server, cacheable communications 
protocol -- and in virtually all cases, the HTTP protocol is used
 
The REST architectural style constrains an architecture to
a client/server architecture and is designed to use a stateless communication protocol, typically
HTTP. In the REST architecture style, clients and servers exchange representations of resources
by using a standardized interface and protocol.  
 
REST is almost always going to be faster. The main advantage of SOAP is that it provides a mechanism for services to describe themselves to clients, and to advertise their existence.
REST is much more lightweight and can be implemented using almost any tool, leading to lower bandwidth and shorter learning curve. However, the clients have to know what to send and what to expect.
In general, When you're publishing an API to the outside world that is either complex or likely to change, SOAP will be more useful. Other than that, REST is usually the better option.
 
 
The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object (in practice most of the services use a POST for this).

Who's using REST?
All of Yahoo's web services use REST, including Flickr, del.icio.us API uses it, pubsub, bloglines, technorati, and both eBay, and Amazon have web services for both REST and SOAP.

Who's using SOAP?
Google seams to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.

REST vs SOAP
As you may have noticed the companies I mentioned that are using REST api's haven't been around for very long, and their apis came out this year mostly. So REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (lets face it you use soap to wash, and you rest when your tired).

http://www.drdobbs.com/web-development/restful-web-services-a-tutorial/240169069

EXAMPLES

 

Calling REST API From PHP – The Easy Way

REST API provides external interface to call some important functions of any Web based software. It’s very easy to write and test applications with REST APIs. Let’s say that we are building an application that we want to automatically upload an image file and submit a form data. We can perform this work through some APIs if provided. We suppose sample REST APIs and then write the code to call these REST APIs. We will use on the POST method for sending data to the server.

Sample REST API

The first for any REST API is the URLs. We assume our base URL to be:
 http://yourwebsite.com/rest 
Authentication information is also required for calling secure web services. We suppose following:
 
username: username
password: secret
We also need the information about REST API functions that we need to call. We assume following two REST functions.
Method: Image_Upload

Input Parameters:
* title - Name of the image 
* media: Path to the image file preceeded by a @ sign

Output:
Returns json encoded string containing true and image_id if successful. 
Method: Contact_Create

Input Parameters:
* first_name
* last_name
* email

Output:
Returns json encoded string containing contact_id if successful.

Authentication and Preparing Request

Every REST API call requires authentication before calling the web service method. Following function rest_api_call is used by clients to authenticate requests to the REST API. It will also prepare the request and carry the request to REST Web Service. It has two arguments. First argument is the name of the API method, where as second argument takes an array containing the input data to the method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function rest_api_call($method, $arguments = array()) {
  $api_url  = 'http://yourwebsite.com/rest';
  $username = 'myuser';
  $password = 'mysecret';
  $service_url = "$api_url/$method?username=$username&password=$password";
  $curl = curl_init($service_url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  foreach($arguments as $key=> $value) {
    if(is_array($value)){
      $arguments[$key] = json_encode($value);
    }
  }
  curl_setopt($curl, CURLOPT_POSTFIELDS, $arguments);
  $curl_response = curl_exec($curl);
  curl_close($curl);
  return json_decode($curl_response); 
}

Prepare Arguments and Call rest_api_call()

In this section, concrete example is given to demonstrate how to prepare arguments and then call rest_api_call function.
This example uploads image file. Here first argument is created in an array. Argument array contains name and value pairs. Names like ‘title’ and ‘media’ are the input parameters of the REST function Image_Upload. While ‘myimage’ and ‘@testpath/img.jpg’ are the values that will passed to the Image_Upload function. Then rest_api_call() is called by passing the arguments array and the REST method name i.e. Image_Upload.
1
2
3
4
5
6
7
$arguments = array(
 'title' => 'myimage',
 'media' => '@testpath/img.jpg',
);
$result = rest_api_call('Image_Upload', $arguments);
$result = $result[1];
$img_id = $result->img_id;
Similarly another REST API call code is given below.
1
2
3
$arguments = array('first_name'=>'chulbul', 'last_name'=>'pandey','email'=>'info@mymail.com');
$result  = rest_api_call('Contact_Create', $arguments);
$contact = $result[1];
As you see above, calling a REST API code reduces to just three lines of code. The authentication and preparing request part is written just once in rest_api_call method.
This is post demonstrates the client-side code of REST APIs. The Server-side code for the Upload_Image and Contact_Create functions are not shown. It is assumed while calling the Web services that the client is only familiar with Web service name, its input arguments and output values. That is why we have only focused on these things and to make it look that calling REST web services is very simple and easy.

Programming Simple REST Web services with PHP

 

REST web service is best suitable for Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability. In the REST architectural style, data and functionality are considered resources and are accessed using URIs, typically links on the Web.
Why we ever need REST web services? Most modern applications integrate data from sources other than user forms. One standard approach to integrating data from outside sources is to use a RESTful endpoint to accept JSON data. Custom approach for developing REST web services works well if you want to integrate existing custom applications (or CMS such as Drupal or WordPress) and some third party application. This post will document how to program your own REST API to accept JSON via POST.

File Structure

rest
├── Controllers
│   ├── dbconnect.php
│   ├── api
│   │   ├── Contact.php (user defined controllers)
│   │   └── MyController.php
├── index.php
└── Rest.php

Define URI

First step to develop REST API server requires defining URI format. For simplicity, I leave it to default GET and POST method implementation. All the rules are defined in Rest.php. A URL request first comes to index.php and it then forwards that request for further handling and authentication to Rest.php. Following the format of the default URI for calling the REST APIs.
http://localhost/rest/?RESTurl=test&method=contact
Its better to accept arguments in your URI in order to provide a more dynamic API that can serve all your POST needs. Our function will be responsible for validating the request, accepting a PHP input stream, returning status codes, decoding the JSON and processing the data into database before returning a response code of success.

Validation

For minimum validation consider validating the request as a POST, authenticating a specific user, or key and performing data validation for data type and data structure (field and object validation).
When authenticating a user, or key, one option is to pass the information via the header userpwd.
Curl request with userpwd:
curl --user username:password -X POST -d @file.txt --header "Content-Type: application/json" http://yourapp.com/api/v1/post/json/
In order to check for the username and password from the example above use PHP’s $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PWD’]. If you are only validating on a key you can pass the key as the username and validate the username in your application.
In this case, we are passing the authentication username and apikey as arguments. That will be validated with database in checkAuth() function in Rest.php.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public function checkAuth() {
 $name=$_GET['name'];
 $apikey=$_GET['apikey'];
 $users=mysql_query("select * from users where name='$name'");
 
 while($row = mysql_fetch_array($users))
 {
   if($apikey==$row['api_key']){
    return true;
   }
   else{
    return false;
   }
}
In this function above, we have taken two authentication arguments from API caller i.e. name (username) and apikey. These two values can the authenticated with database or any config file to check that the requested user is authorized to call these APIs.

Processing the JSON

Once the authentication is successful, the request moves to the called method. PHP provides a method to obtain stream inputs by using file_get_contents and requesting “php://input”. File_get_contents streams the input and processes it into a string. Once the input is returned as a string use PHPs json_decode to return the string as an associative array.
 $received_json = file_get_contents("php://input",  TRUE);
 $json = drupal_json_decode($received_json, TRUE);
Note: Consider detecting if json_decode returns null or false.
Once validation has passed and your JSON is available, iterate and save the object to Drupal.
1
2
3
4
5
6
7
8
9
10
11
12
13
class contact{
  public function post(){
    $json = file_get_contents('php://input');
    $obj = json_decode($json,true);
    $name= $obj["first_name"];
    $last=$obj["last_name"];
    $email=$obj["email"];
    $fax=$obj["fax"];
    $result=mysql_query("select * from users");
    $result = mysql_fetch_array($result);
    return $result;
  }
}
After completing the payload a notice of success to inform the application it’s POST was a success.

Calling the REST API Function

Finally, your REST API server is ready to be called. Calling an API function requires the function name and an array of correctly formatted values and keys so that JSON can decode it at the receiving end. Following is a sample code we used in calling our REST API contact function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$data = array("first_name" => "falak", "last_name" =>"nawaz","email"=>"saynotospam@mymail.com");
$method="contact";
$result=apicall($method,$data);
$result=$result[1];
print_r($result);
 
function apicall($method,$data_string){
$api_url  = 'http://localhost/rest';
$username = $_POST['username'];
$key=$_POST['apikey'];
 
$service_url = "$api_url/?RESTurl=test&method=$method&name=$username&apikey=$key";
//curl_setopt($curl,CURLOPT_HEADER,true);
//curl_setopt($curl, CURLOPT_HTTPHEADER,$headers );
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($data_string));
$curl_response = curl_exec($curl);
curl_close($curl);
return json_decode( $curl_response);
}
Download the complete source code: Download
Programming your own RESTful endpoint is simple, is light on code count and provides flexibility.

 

How to convert Text-to-Speech with PHPhttp://sourcecodemania.com/how-to-convert-text-to-speech-with-php/

http://sourcecodemania.com/reading-and-printing-contents-of-an-xml-file-using-php/

 





 

No comments:

Post a Comment