Working with RESTful Services in CodeIgniter

http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/


CodeIgniter is becoming well known for its power as a PHP based web application framework, but it’s not often that we see examples of it being used for anything else. Today we’ll learn how we can use CodeIgniter to create a RESTful API for your existing web applications, and demonstrate how to interact with your own API or other RESTful web-services, such as Facebook and Twitter.

Tutorial Details

  • Program: CodeIgniter, CodeIgniter REST server and CodeIgniter REST client
  • Difficulty: Medium
  • Estimated Completion Time: 30 minutes

Introduction

If you have been following the CodeIgniter From Scratch series you will know by now that it is relatively quick and easy to put together simple web applications, such as blogs, CMS systems, brochure sites, etc. One thing you may not have thought about is using CodeIgniter to create an interactive API. After trying several existing REST implementations, I found they not only lacked simplicity but were missing most of the features you would expect from a RESTful implementation; so I built my own. This tutorial will show you how to use this code to set up your REST API, and gives example of how to interact with it from your web application.

Assumptions

  1. You have a web server set up, locally or online and known how to manage files on it.
  2. You have read a few of the CodeIgniter from Scratch tutorials.
  3. You know how to set up CodeIgniter.
  4. You know a little about RESTful services.

This tutorial is broken down into two parts. We will start by learning how to create a RESTful service, then further down, we will learn how to interact with it in a few different ways.

Part 1 – Creating a RESTful API

Step 1: Setting up the Demo

Firstly you need to download the codeigniter-restserver code from GitHub and extract it and move the code to your server.

When you open the folder, you will see an entire CodeIgniter install, which is there to power the demo. This allows people to have a play with the REST demo before integrating with your existing application.

Open up “application/config/config.php” and set the base_url to get links working. This base_url will be different for everyone and depends entirely on where you uploaded your files.

Step 2: The URLs

With the files extracted and the base_url set, we are ready to load up our RESTful CodeIgniter installation, and have a look at the demo supplied with it. Browse the base URL, which by default is:

http://localhost/restserver

Here you will find a few example links to the example_api controller, which can be found at“application/controllers/example_api.php”. Let’s dissect the URL’s of these examples to see what is going on. The first URL is a very simple one.

Working with RESTful Services in CodeIgniter_第1张图片

This URL looks very much like any other CodeIgniter URL with a controller and a method, but you will notice in this diagram that the method is named a “Resource”. REST is all about Resources and they are essentially a noun within your application, which are interacted with (i.e added, deleted, edited, queried) based on HTTP headers and URL query strings or HTTP arguments.

The default format for output is XML which is what we see in this basic example. The other links are slightly larger and demonstrate how to pass parameters and show how the output format can be modified in the URL:

Working with RESTful Services in CodeIgniter_第2张图片

Normally in CodeIgniter, you just pass in parameter values, but a REST controller accepts any number of parameters in any order. For this to work, we need to pass in the name of the parameter followed by the value in pairs.

At the end of the URL is the “format” parameter. This is a reserved parameter that will modify the output format of the requested data like so:

By giving both the API developer and the client application the choice of data formats to use, the API is opened up to a much wider audience and can be used with more programming languages and systems. These three are not the only formats supported, out of the box your REST API can use:

  • xml – almost any programming language can read XML
  • json – useful for JavaScript and increasingly PHP apps.
  • csv – open with spreadsheet programs
  • html – a simple HTML table
  • php – Representation of PHP code that can be eval()’ed
  • serialize – Serialized data that can be unserialized in PHP

While adding the format to the URL is not technically the most RESTful way to change formats, it allows for easy browser testing and lets developers without cURL perform simple GET requests on the API. The more RESTful way is to send a Content-type HTTP header to the REST controller using cURL, but that will be explained later.

Step 3: The Code

Now if you open up application/controllers/example_api.php you will immediatley spot a few differences from normal CodeIgniter controllers.

REST_Controller

In the MVC pattern, a controller is the central point of the logic. It is called when a user makes a request and then based on the logic in the controller it fetches data and outputs views. CodeIgniter contains its own logic for how a Controller should work, but as we are doing something different we need our own REST_Controller library to contain its own REST related logic. So instead of simply using:

view plain copy to clipboard print ?
  1. <?php  
  2. class Example_api extends Controller {  
  3.   
  4. }  

…you will need to use:

view plain copy to clipboard print ?
  1. <?php  
  2. require(APPPATH'.libraries/REST_Controller.php');  
  3.   
  4. class Example_api extends REST_Controller {  
  5.   
  6. }  

Working with Resources

Now your empty controller is set up, next are the methods or “resources”. This is prossibly the most confusing part of the tutorial if you are used to how CodeIgniter works. Basically, you take the Resource and the HTTP verb and combine them to make a method name. So the two examples we looked at before had a Resource of user and users. Because both of these were loaded in the browser, we know it was using a GET request and so the two methods below are used:

view plain copy to clipboard print ?
  1. <?php  
  2. require(APPPATH'.libraries/REST_Controller.php');  
  3.   
  4. class Example_api extends REST_Controller {  
  5.   
  6.     function user_get()  
  7.     {  
  8.         // respond with information about a user  
  9.     }  
  10.       
  11.     function users_get()  
  12.     {  
  13.         // respond with information about several users  
  14.     }  
  15. }  

This may seem a little strange, but it gives you the ability to use the same URL and respond to the request depending on the HTTP verb that has been used. If somebody tries to access your API in a way that is not allowed (in this example PUT or DELETE) it will simply respond with a 404. If you aren’t sure about HTTP verbs, let me explain.

GET

Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it perfect for fetching information on one of your REST resources (like user).

POST

Used to update an existing resource with information. Browsers use this to submit most types of forms on the internet, although some use GET as well by submitting the form action with a query string containing the field data.

PUT

Less commonly used and not supported by most browsers, PUT is used to create a new resource.

DELETE

Also not used by many browsers, this HTTP verb rather obviously is used to delete a resource.

If we put that into code and allow each verb on the resource user it would look like this:

view plain copy to clipboard print ?
  1. <?php  
  2. require(APPPATH'.libraries/REST_Controller.php');  
  3.   
  4. class Example_api extends REST_Controller {  
  5.   
  6.     function user_get()  
  7.     {  
  8.         // respond with information about a user  
  9.     }  
  10.   
  11.     function user_put()  
  12.     {  
  13.         // create a new user and respond with a status/errors  
  14.     }  
  15.   
  16.     function user_post()  
  17.     {  
  18.         // update an existing user and respond with a status/errors  
  19.     }  
  20.   
  21.     function user_delete()  
  22.     {  
  23.         // delete a user and respond with a status/errors  
  24.     }  
  25. }  

Accessing parameters and returning data

So now the API has been given its structure by setting up the resources and defining a method for each HTTP verb we wish to support; we need parameters so we can use our CodeIgniter models and libraries. This is one of the major benefits of using CodeIgniter for our API, as we can use our existing models and libraries and not have to re-code them.

view plain copy to clipboard print ?
  1. <?php  
  2. require(APPPATH'.libraries/REST_Controller.php');  
  3.   
  4. class Example_api extends REST_Controller {  
  5.   
  6.     function user_get()  
  7.     {  
  8.         $data = array('returned: '$this->get('id'));  
  9.         $this->response($data);  
  10.     }  
  11.       
  12.     function user_post()  
  13.     {         
  14.         $data = array('returned: '$this->post('id'));  
  15.         $this->response($data);  
  16.     }  
  17.   
  18.     function user_put()  
  19.     {         
  20.         $data = array('returned: '$this->put('id'));  
  21.         $this->response($data;  
  22.     }  
  23.   
  24.     function user_delete()  
  25.     {  
  26.         $data = array('returned: '$this->delete('id'));  
  27.         $this->response($data);  
  28.     }  
  29. }  

This example contains five new pieces of code:

$this->get()

Is used to return GET variables from either a query string like this index.php/example_api/user?id=1 or can be set in the more CodeIgniter’esque way with index.php/example_api/user/id/1.

$this->post()

Is an alias for $this->input->post() which is CodeIgniter’s method to access $_POST variables with XSS protection.

$this->put()

Reads in PUT arguments set in the HTTP headers or via cURL.

$this->delete()

You guessed it, this reads in DELETE arguments, also set in HTTP headers or via cURL.

$this->response()

Sends data to the browser in whichever data format has been requested, or defaults to XML. You can optionally pass a HTTP status code to show it has worked or failed. E.g if the ID provided was not in the database, you could use $this->response(array(‘error’ => ‘User not found.’), 404);

Step 4: Working with your Models

Until now, we have been working with an example API in a clean install. So the next step is to get a REST API running from your existing codebase.

Although the download comes with a full CodeIgniter installation for the demo and to allow API’s to be built from scratch, the only two files of importance are:

  1. application/config/rest.php
  2. application/libraries/REST_Controller.php

Drop those two files into your CodeIgniter application and create a new API controller.

view plain copy to clipboard print ?
  1. <?php  
  2. require(APPPATH.'/libraries/REST_Controller.php');  
  3.   
  4. class Api extends REST_Controller  
  5. {  
  6.     function user_get()  
  7.     {  
  8.         if(!$this->get('id'))  
  9.         {  
  10.             $this->response(NULL, 400);  
  11.         }  
  12.   
  13.         $user = $this->user_model->get( $this->get('id') );  
  14.           
  15.         if($user)  
  16.         {  
  17.             $this->response($user, 200); // 200 being the HTTP response code  
  18.         }  
  19.   
  20.         else  
  21.         {  
  22.             $this->response(NULL, 404);  
  23.         }  
  24.     }  
  25.       
  26.     function user_post()  
  27.     {  
  28.         $result = $this->user_model->update( $this->post('id'), array(  
  29.             'name' => $this->post('name'),  
  30.             'email' => $this->post('email')  
  31.         ));  
  32.           
  33.         if($result === FALSE)  
  34.         {  
  35.             $this->response(array('status' => 'failed'));  
  36.         }  
  37.           
  38.         else  
  39.         {  
  40.             $this->response(array('status' => 'success'));  
  41.         }  
  42.           
  43.     }  
  44.       
  45.     function users_get()  
  46.     {  
  47.         $users = $this->user_model->get_all();  
  48.           
  49.         if($users)  
  50.         {  
  51.             $this->response($users, 200);  
  52.         }  
  53.   
  54.         else  
  55.         {  
  56.             $this->response(NULL, 404);  
  57.         }  
  58.     }  
  59. }  
  60. ?>  

This shows an example API with some generic model names. In the first method, we are picking up a ?id=XX and passing it to the model. If data is found we send it to the $this->response() function with a status 200. If nothing is found, return no body and a 404 to say nothing was found. You can imagine how this could be expanded to run all sorts of API activities for your web application.

Step 5: Securing the API

Now your API is built it needs securing so only users given access can interact with the API. To set the login type, usernames and passwords open up “application/config/rest.php” inside your codebase.

view plain copy to clipboard print ?
  1. /* 
  2. |-------------------------------------------------------------------------- 
  3. | REST Login 
  4. |-------------------------------------------------------------------------- 
  5. | 
  6. | Is login required and if so, which type of login? 
  7. | 
  8. |   '' = no login required, 'basic' = relatively secure login, 'digest' = secure login 
  9. | 
  10. */  
  11. $config['rest_auth'] = 'basic';  

None

Anyone can interact with any one of of your API controllers.

Basic

A relatively insecure login method which should only be used on internal/secure networks.

Digest

A much more secure login method which encrypts usernames and password. If you wish to have a protected API which anyone could get at, use digest.

view plain copy to clipboard print ?
  1. /* 
  2. |-------------------------------------------------------------------------- 
  3. | REST Login usernames 
  4. |-------------------------------------------------------------------------- 
  5. | 
  6. | Array of usernames and passwords for login 
  7. | 
  8. |   array('admin' => '1234') 
  9. | 
  10. */  
  11. $config['rest_valid_logins'] = array('admin' => '1234');  

Setting up the users is simple. Each login is an array item, with a key and a value. The key is the username and the value is the password. Add as many as you like to this array and dish them out to anyone who will be using the API.

Part 2 – Interacting with RESTful Services

Whether it is the API you have just built or a public service such as Twitter, you will want to be able to interact with it somehow. Seeing as RESTful services work with basic HTTP requests it is very easy to do this in a number of different ways.

Different Methods to Interact with REST

Each of these different interaction methods will be shown with the code placed directly in the Controller methods. This is purely so the demos are easier to read and would normally would be placed inside a model or a library for correct MVC separation.

file_get_contents()

Using the very simple PHP function file_get_contents(), you can perform a basic GET request. This is the most basic of all the methods but is worth mentioning for those “quick and dirty” moments.

view plain copy to clipboard print ?
  1. $user = json_decode(  
  2.     file_get_contents('http://example.com/index.php/api/user/id/1/format/json')  
  3. );  
  4.   
  5. echo $user->name;  

It’s worth noting that, while this method will not work using HTTP Digest authentication, if you are using HTTP Basic authentication you can use the following syntax to get data from your password protected RESTful API:

view plain copy to clipboard print ?
  1. $user = json_decode(  
  2.     file_get_contents('http://admin:[email protected]/index.php/api/user/id/1/format/json')  
  3. );  
  4.   
  5. echo $user->name;  

There are a few problems with using this method: the only way to set extra HTTP headers is to set them manually using the PHP function stream_context_create(), which can be very complicated for developers who are new to the internal workings of HTTP requests. Another disadvantage is that you only receive the body of the HTTP response in its raw format, which means you need to handle conversion from very single request.

cURL

cURL is the most flexible way to interact with a REST API as it was designed for exactly this sort of thing. You can set HTTP headers, HTTP parameters and plenty more. Here is an example of how to update a user with our example_api and cURL to make a POST request:

view plain copy to clipboard print ?
  1.   function native_curl($new_name$new_email)  
  2.   {  
  3.    $username = 'admin';  
  4. $password = '1234';  
  5.   
  6. // Alternative JSON version  
  7. // $url = 'http://twitter.com/statuses/update.json';  
  8. // Set up and execute the curl process  
  9. $curl_handle = curl_init();  
  10. curl_setopt($curl_handle, CURLOPT_URL, 'http://localhost/restserver/index.php/example_api/user/id/1/format/json');  
  11. curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);  
  12. curl_setopt($curl_handle, CURLOPT_POST, 1);  
  13. curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array(  
  14.     'name' => $new_name,  
  15.     'email' => $new_email  
  16. ));  
  17.   
  18. // Optional, delete this line if your API is open  
  19. curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password);  
  20.   
  21. $buffer = curl_exec($curl_handle);  
  22. curl_close($curl_handle);  
  23.   
  24. $result = json_decode($buffer);  
  25.   
  26. if(isset($result->status) && $result->status == 'success')  
  27. {  
  28.     echo 'User has been updated.';  
  29. }  
  30.   
  31. else  
  32. {  
  33.     echo 'Something has gone wrong';  
  34. }  
  35.   }  

Interacting with your API this way works fine, but there are two problems with this method:

  1. It uses an ugly confusing syntax – imagine creating several an application based on that.
  2. cURL is not installed on all servers by default.

To solve this ugly syntax, a cURL library has been developed for CodeIgniter which simplifies things immensely.

The exact same request made with the cURL library would look like this:

view plain copy to clipboard print ?
  1.   function ci_curl($new_name$new_email)  
  2.   {  
  3.    $username = 'admin';  
  4. $password = '1234';  
  5.   
  6. $this->load->library('curl');  
  7.   
  8. $this->curl->create('http://localhost/restserver/index.php/example_api/user/id/1/format/json');  
  9.   
  10. // Optional, delete this line if your API is open  
  11. $this->curl->http_login($username$password);  
  12.   
  13. $this->curl->post(array(  
  14.     'name' => $new_name,  
  15.     'email' => $new_email  
  16. ));  
  17.   
  18. $result = json_decode($this->curl->execute());  
  19.   
  20. if(isset($result->status) && $result->status == 'success')  
  21. {  
  22.     echo 'User has been updated.';  
  23. }  
  24.   
  25. else  
  26. {  
  27.     echo 'Something has gone wrong';  
  28. }  
  29.   }  

Much nicer to look at right? Well there is an even easier method to work with REST in your CodeIgniter applications that this.

REST client library

A REST client library has been developed that sits on top of this cURL library which handles format conversion, HTTP logins and several other aspects of your REST API.

view plain copy to clipboard print ?
  1.   function rest_client_example($id)  
  2.   {  
  3. $this->load->library('rest'array(  
  4.     'server' => 'http://localhost/restserver/index.php/example_api/',  
  5.     'http_user' => 'admin',  
  6.     'http_pass' => '1234',  
  7.     'http_auth' => 'basic' // or 'digest'  
  8. ));  
  9.   
  10.       $user = $this->rest->get('user'array('id' => $id), 'json');  
  11.         
  12.       echo $user->name;  
  13.   }  

Here you can see we are making a GET request, sending id as a parameter and telling the library we want ‘json’ as the content format. This handles the setting of Content-type for you, and converts the data into a PHP object for you. You can change this value to ‘xml’, ‘json’, ‘serialize’, ‘php’, ‘csv’ or any custom MIME-type you like, for example:

view plain copy to clipboard print ?
  1. $user = $this->rest->get('user'array('id' => $id), 'application/json');  

As you have probably guessed as well as $this->rest->get(), the library also supports $this->rest->post(), $this->rest->put(), $this->rest->delete() to match all of your REST_Controller methods.

You will need to var_dump() results coming from the REST client library to make sure you are getting the right data format back. The conversion will somtimes be array and sometimes be an object, depending on how it is converted by PHP. If the returned MIME-type is not supported then it will simply return the format as plain-text.

Talking to Twitter

Using this REST library you can talk other RESTful services such as Twitter and Facebook. Here is a simple example of how you can get details for a specfic user based on their ID, using Twitter’s default format XML.

view plain copy to clipboard print ?
  1. $this->load->library('rest'array('server' => 'http://twitter.com/'));  
  2.   
  3. $user = $this->rest->get('users/show'array('screen_name' => 'philsturgeon'));  
view plain copy to clipboard print ?
  1.      $this->load->library('rest'array(  
  2.         'server' => 'http://twitter.com/',  
  3. 'http_user' => 'username',  
  4. 'http_pass' => 'password',  
  5. 'http_auth' => 'basic'  
  6.      ));  
  7.   
  8.      $user = $this->rest->post('statuses/update.json'array('status' => 'Using the REST client to do stuff'));  

Looking at this, you will notice that interacting with the Twitter API is a bit different in a few ways.

  1. They support URL based format switching in the form of .json instead of /format/json. Some require an extension, some do not; so it’s best to always add them.
  2. They mostly only support GET/POST, but are starting to add more DELETE methods
  3. They don’t always have just a resource in their URL, for example: users/search is one REST method, but lists is another.

Keep an eye out for these differences as they can catch you out. If you get stuck, simply echo $this->rest->debug() for a whole range of information on your REST request.

Summary

Combining what you now know about RESTful services, the CodeIgniter REST client library and the Twitter API documentation – or any other RESTful API documentation for that matter – you can create some very powerful applications that integrate with any custom or public web service using REST. You can extend your API by creating more REST_Controller’s and even make a modular API by using Matchbox or Modular Separation to create an api.php controller for each module to help keep your API as neatly organized as your application.

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us?We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at [email protected].

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.


你可能感兴趣的:(api,user,REST,basic,Parameters,library)