[Yii Framework] Make a Client Rest Application (GET)

Pada website yii framework telah ada sebuah wiki yang membahasa cara membuat rest service dengan Yii Framework. Pada wiki itu juga di sertakan aplikasi contoh yang telah menerapkan rest service pada aplikasinya dan dapat kita download langsung pada link yang ada pada wiki tersebut. Hanya saja walaupun telah ada aplikasi contoh yang menerapkan rest service, banyak orang mengalami kesulitan untuk membuat aplikasi client yang mengakses rest service nya dengan Yii Framework. Maka dari itu kali ini saya akan memaparkan cara untuk membuat client rest service pada Yii Framework. Tapi perlu diketahui posting kali ini hanya membahas pengaksesan data pada “GET” saja (biar ga kepanjangan).. Berikut step-step nya :

Sebelum lebih jauh, saya asumsikan anda sudah paham apa itu rest service karena saya tidak akan menjelaskan lagi tentang rest.

1. Agar seragam silahkan terlebih dahulu  mendownload aplikasi yang telah ada pada tutor Yii Fraemework di http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api/. Jika sudah di download letakkan pada server local anda dan pastika aplikasi nya bisa dijalankan.

2. Craete new application in Yii Framework

3. Buatlah sebuah fungsi untuk mengakses rest service :

// terdapat 3 buah parameter, data sebagai parameter data, url untuk mengetahui akan mengakses url mana service nya, method untuk mengetahui apa metode yang digunkana (post, get, put)
public $password="password service nya";
public $usernama="username service nya";
public function submit_cURL ($data,$url,$method) 
 {
   $data[]="X_ASCCPE_PASSWORD : $this->password"; // data untuk autentikasi password
   $data[]="X_ASCCPE_USERNAME : $this->username"; // data untuk autentikasi username
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
   if($method=='POST')
      curl_setopt($ch, CURLOPT_POST, 1);
   else if($method=='PUT')
      curl_setopt($ch, CURLOPT_PUT, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
   $result = curl_exec($ch);
   curl_close ($ch);

   return $result;
 }

4. Code sebelumnya adalah fungsi untuk memanggil rest service, untuk menampilkan rest service nya buatlah pada suatu action. Service  pertama yang akan kita akan panggil rest service nya adalah action list dimana akan menampilkan semua data pada service. Pada aplikasi yang telah kita donlod sebelumnya kita bisa melihat di dalamnya terdapat sebuah folder “Rest Client Request”. Kita dapat melihat request pada “list” adalah seperti berikut :

{"requestUrl":"http://localhost/~diggindata/yii-blog-rest/index.php/api/posts","requestMethod":"GET","requestBody":"","headers":["X_ASCCPE_PASSWORD","demo","X_ASCCPE_USERNAME","demo"]}

Agar dapat mengakses nya, buatlah action seperti berikut pada controller anda :

public function actionList()
 {
   $data[]='';
   $result=$this->submit_cURL($data,"http://localhost/yii-blog-rest/index.php/api/posts","GET"); // memanggil fungsi yang menampilkan rest service dengan memasukkan beberapa parameter
   print_r($result);
 }

Jika sudah silahkan jalankan maka akan menghasilkan hasil berupa data-data seperti berikut :

[{"id":"1","title":"Welcome!","content":"This blog system is developed using Yii. It is meant to demonstrate how to use Yii to build a complete real-world application. Complete source code may be found in the Yii releases.\n\nFeel free to try this system by writing new posts and leaving comments.","tags":"yii, blog","status":"2","create_time":"1230952187","update_time":"1230952187","author_id":"1"},{"id":"2","title":"A Test Post","content":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.","tags":"test","status":"2","create_time":"1230952187","update_time":"1230952187","author_id":"1"},{"id":"10","title":"XXX","content":"YYY","tags":"","status":"1","create_time":"1302873156","update_time":"1302873156","author_id":"1"},{"id":"12","title":"XXX","content":"YYY","tags":"","status":"1","create_time":"1302873243","update_time":"1302873243","author_id":"1"},{"id":"13","title":"XXX","content":"YYY","tags":"","status":"1","create_time":"1302873251","update_time":"1302873251","author_id":"1"},{"id":"14","title":"XXX 222","content":"Bla","tags":"","status":"1","create_time":"1302894646","update_time":"1302894646","author_id":"1"}]

Setelah itu kita juga akan coba mengakses view, dimana bisa kita lihat request dari view adalah seperti berikut :

{"requestUrl":"http://localhost/~diggindata/yii-blog-rest/index.php/api/posts/1","requestMethod":"GET","requestBody":"","headers":["X_ASCCPE_PASSWORD","demo","X_ASCCPE_USERNAME","demo"]}

Anda bisa lihat beda nya pada view memiliki parameter id yang ingin di view. Agar dapat menampilkannya, silahkan buat sebuah action kembali dengan code seperti berikut :

public function actionView($id)
 {
   $data[]='';
   $result=Yii::app()->srest->submit_cURL($data,"http://localhost/yii-blog-rest/index.php/api/posts/$id","GET");
   print_r($result);
 }

Kemudian cobalah akses action tersebut, maka akan tampil data seperti berikut (misal untuk id=2):

{"id":"2","title":"A Test Post","content":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.","tags":"test","status":"2","create_time":"1230952187","update_time":"1230952187","author_id":"1"}

Selesai… Selamat mencoba..
semoga membantu…

[Yii Framework] Use Javascript LinkedIn Api

We have know that linkedin allow developer for access their data with their API service. In this step, i will make a case about “how to create search people with linkedin api”. This is screenshoot my aplication linkedin search.

This is some step we must do for use javascript linkedin api for our website in Yii Framework.

1. Create an application in linkedin web : https://www.linkedin.com/secure/developer. You must complete your data application and then you will get API key and secret key.

2. Create an action in your controller and then make a code :

public function actionLinkedin($username=NULL,$page=0)
{

   if(isset($_POST['username']))
   {  
      if(isset($_POST['page']))
      {
         if(is_numeric($_POST['page']))
             $this->redirect(array('linkedin','username'=>$_POST['username'],'page'=>((int)$_POST['page']-1)));
         else
             $this->redirect(array('linkedin','username'=>$_POST['username'])); 
      }
      else
      {
           $this->redirect(array('linkedin','username'=>$_POST['username']));
      }
   }

    $this->render('linkedin');
 }

3. In your view, make code for your form view :

<h1>LinkedIn Search</h1>
<div id="wrapper">
  <div id="searchbar">
  <?php $form=$this->beginWidget('CActiveForm', array(
     'id'=>'searchform',
     'method'=>'POST'
  )); ?>
      <fieldset class="text ui-widget-content ui-corner-all">
          <label for="name">Keywords : </label>
          <input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all" />

          <label for="name">Page : </label>
          <?php echo CHtml::dropDownList('page','',array(),array('empty'=>'-- Select --')); ?>

          <input type="submit" value="Search">
      </fieldset>

      <div id="buttons"></div>
   <?php $this->endWidget(); ?>
   </div>
   <script type="IN/Login" data-onAuth="loadData"></script>
   <div id="connections"></div>
</div>

4. Call linkedin js with your key :

<script type="text/javascript" src="http://platform.linkedin.com/in.js">
 api_key: your_api_key 
 authorize: true
</script>

5. Create a code in your view, for do some operation for your search linkedin..

<script type="text/javascript"> 

 function loadData()  // function for load search data
 {
   var searchName;
   var halaman;
   locations = [];
   if (window.location.toString().split("&").length > 1) // if in URL have parameter, then use that parameter for keyword search
   {
      searchName = window.location.toString().split("&")[1].split("=")[1].replace("+"," ");
   }
   else 
   {
      searchName = "default_keyword";  // if in URL have not parameter, user this default keyword for search
   }

   if (window.location.toString().split("&").length > 2) // if in URL have a "page" parameter, then user that parameter for page search
   {
      halaman = window.location.toString().split("&")[2].split("=")[1].replace("+"," ");
   }
   else 
   {
      halaman=0; // if in parameter have not parameter page, then default page is "0"
   }

   $("#username").val(searchName) // set username value

   // some url for call API search in linkedin, you must read linkedin api documentation for know about this
   url = "/people-search:" +
     "(people:(id,firstName,lastName,pictureUrl,industry,publicProfileUrl,headline,location,positions))" +
     "?start="+(halaman*20)+"&count=20&keywords=" + searchName 

   // some function from linkedin for do search
   IN.API.Raw(url)
     .result(function(result) {
        $.ajax({
        url: "<?php echo Yii::app()->createUrl('ControllerName/ActionName')?>", // we want to know how many page we get from result searh for use in choice of page. In this case we will use ajax and call our action
        data: "haha=" + result.people._total,  // parameter that sent total people from search result
        success: function(data){  // if success
            $("#page").html(data);  // we set to control page
        }
     });

     // we set some html code for view our result
     halnow=parseInt(halaman)+1;
     profHTML ="Search Result Keyword \""+searchName+"\" page "+halnow;
     profHTML += "<table class=\"maaron\" width=\"100%\"><tr><th>Profile Picture</th><th>Name</th><th>Title at Company</th><th>Company</th><th>Public Profile URL</th><th>View</th></tr>";
     for (var index in result.people.values)
     {
        profile = result.people.values[index] 
        id = profile.id + ":" + profile.firstName + " " + profile.lastName 
        if (profile.pictureUrl)
        {
            profHTML += "<tr><td><img id=\"" + id + "\" border height=30 align=\"left\" src=\"" + profile.pictureUrl + "\"></td>";
        }
        else
        {
            profHTML += "<tr><td><img id=\"" + id + "\" border height=30 align=\"left\" src=\"http://static02.linkedin.com/scds/common/u/img/icon/icon_no_photo_60x60.png\"></td>"; 
        }
        profHTML += "<td>"+profile.firstName + " " + profile.lastName + "</td>";
        profHTML += "<td>"+profile.headline + "</td>";
        profHTML += "<td>"+ profile.industry + "</td>";
        profHTML += "<td><a href="+ profile.publicProfileUrl +" target='_blank'>Public Link</a></td>";
        profHTML += "<td><a href='?r=search/linkview&id="+profile.id+"'>View</a></td></tr>";
    }
    profHTML+="</table>";
    $("#connections").html(profHTML);
   });
 }

 $("#searchbar").keypress(function(e) // event when user input some keyboard
 {
    if (e.keyCode == 13) { // when user input "enter"
       e.preventDefault();
       if ($("#username").val() != "") 
       {
         loadData();
         return false;
       }
    }
  });
</script>

6. Because we have some action that call AJAX for set the page choice, then we must create that action. So in your controller, create an action like this :

public function actionTarik()
 {
   $haha = $_GET["haha"];
   $totalhalaman=$haha/20+1;
   echo "<option>-- Select --</option>";
   for($i=1;$i<=$totalhalaman;++$i)
   {
       echo '<option value='.$i.'>'.$i.'</option>';
   }
 }

Finsihed.. Hope help you.. 😀
Sorry for my bad English..

%d bloggers like this: