Powered by Blogger.

Contact

Popular Posts

Saturday 24 August 2013


Create your own API with Restler

Create your own API with Restler


  • Knowledge needed: Intermediate PHP, basic MySQL
  • Requires: PHP 5.3 or greater with cURL enabled, MySQL database
  • Project time: 4-6 hours

HTTP web service APIs are now commonplace: many companies make them available so devs can work with their data. Here Richard Askew takes you through building your own

This article first appeared in issue 235 of .net magazine – the world's best-selling magazine for web designers and developers.
A HTTP web service API uses the HTTP methods GET, POST, PUT and DELETE to pass information to exposed objects that perform actions on your data. For example the Joind.in API utilises a GET request to return all past events.

There are many reasons why your users might want to get access to your data or processes, and a well thought out API will help you to achieve this. For example in the company I work for we wanted customers to be able to perform actions, such as resending emails and changing order details that our staff would normally have to do manually.

This tutorial uses an open source program for creating a HTTP web service API, Luracast’s Restler 3.0, to create a very simple API that you can extend with modelled objects.

Hello world

Let’s get things under way: the aim here is to pass a name variable into a URL and output a response to the user. We are going to create a very simple class that accepts a name parameter and displays ‘Hello’ along with the parameter called say.php:
  1. class Say {
  2. function hello($to='world') {
  3. return "Hello $to!";
  4. }
  5. }
Now that we have this ready to go we can begin constructing the index.php script for the API. Start by downloading the Restler code and requiring it from the index page. Then set up the routing – this will enable the use of simple access URLs:
  1. require_once '../vendor/restler.php';
  2. use Luracast\Restler\Restler;
  3. use Luracast\Restler\Defaults;
  4. Defaults::$smartAutoRouting = false;
The next step is to initialise the Restler object and to specify the class that the Restler platform is exposing to the GET request.
  1. $r = new Restler();
  2. $r->addAPIClass('Say');
  3. $r->handle();
There you have it – the Restler platform takes care of the rest when the URL is visited and exposes the following URL:
index.php/say/hello/Richard Askew
Bingo – you have created a class and exposed a method to a URL that returns information to the user. Now let’s move onto something a little more useful and a little more structured.

Result from the first GET request – when you send the name parameter it is appended to a the end of the string and displayed

Next steps

For this example we are going to create an API that enables us to read and manipulate data. First of all we’re going to need to create a simple database. For the time being, create just one table called person with the following fields: person_id, name and email_address.

So this time we’re going to work with a database of people that will be searched, added to, updated and deleted. As in our earlier example we’ll be creating a class that uses a GET request – but this time it models a person. This method takes an ID and returns the information we store about that person in the database. This class references and uses a database class that isn’t going to be covered here – but the files you need are in the support download.
  1. use Luracast\Restler\RestException;
  2. class Person {
  3. static $FIELDS = array('name', 'email_address');
  4. protected $db;
  5. function __construct(){
  6. $this->db = newMysqlDb('host', 'username', 'password', 'database');
  7. }
  8. function get($id=NULL) {
  9. if($id != NULL){
  10. $this->db->where('person_id', $id);
  11. }
  12. $results = $this->db->get('person');
  13. return $results;
  14. }
  15. }
To expose the method to our API we need to create an index file that is very similar to the one used in the ‘hello world’ example. Simply pass Person into your addAPIClass method call instead of Say. You will also need to connect to your database.
  1. require_once '../vendor/restler.php';
  2. use Luracast\Restler\Defaults;
  3. Defaults::$smartAutoRouting = false;
  4. $r = new Restler();
  5. $r->addAPIClass(‘Person’);
  6. $r->handle();
If you now visit the URL localhost/index.php/person/1, Restler uses the GET method – because that’s the HTTP method you are using – and returns the information in our database that matches an ID of 1. If you don’t specify an ID for a person then all records are returned.

The view of the person database in PhpMyAdmin – notice this very simple database has three fields and the person_id is set to auto_increment

Displaying errors

As with all web-based systems providing useful and consistent error codes is extremely important, especially if you are building something that others can integrate into their own systems. Restler allows you to define an error code and output a message to the user. Error codes reflect the HTTP status codes:
  • 1xx - Informational
  • 2xx - Success
  • 3xx - Redirection
  • 4xx - Client Error
  • 5xx - Server Error
  1. function get($id = NULL)
  2. {
  3. if($id != NULL){
  4. $this->db->where('person_id', $id);
  5. }
  6. $results = $this->db->get('person');
  7. if(empty($results) && $id != NULL){
  8. throw new RestException(400, "This ID doesn't exist");
  9. }
  10. return $results;
  11. }
Now if you visit the localhost/index.php/person/10, you should be presented with the error code and error message:

Restler enables errors to be displayed to the user if you wish; when this is thrown the script doesn’t execute any further actions

Formats

You may have noticed that Restler is displaying the data in JSON. This is the default setting, but you can configure your system to return JSON, XML or enable the user to select which one they want to get back. In order to do this, we simply add a new line of code immediately after we call Restler in our index page:
  1. $r->setSupportedFormats('XmlFormat','JsonFormat');
You can see that we have specified XML and JSON, the fact that XmlFormat is listed first means that the data is returned in this format by default. If you now visit localhost/index.php/person/1 the data is returned in XML format and you can switch back to JSON by using the following URL localhost/index.php/person.json/1.

If required the returned data can be displayed in XML format: you pass an array to Restler and it does the rest

Adding data

We have just used the GET method to retrieve data but to realise the full power of our API we need to create content. To do this we make use of the POST method. In our Person class, we are going to create a method that accepts two variables, name and email, and uses them to create a record in our database.
  1. function post($request_data=NULL) {
  2. $insertData = array(
  3. 'name' => $request_data['name'],
  4. 'email_address' => $request_data['email_address']
  5. );
  6. if ( $results = $this->db->insert('person', $insertData) ) return
  7. array('success'=>"Record created");
  8. }
This method will be invoked by posting data to our API; doing this, however, is a little more complicated than visiting a URL. As we are using the POST protocol, your script will need to utilise a library such as cURL. To begin with, initialise the cURL handler and define the location of the API that we are going to post data to:
  1. $ch = curl_init();
  2. curl_setopt($ch, CURLOPT_URL,'http://localhost/index.php/person');
Next, we need to determine that we are going to POST data – specifically the data we are posting – and to expect data back in return:
  1. curl_setopt($ch, CURLOPT_POST,1);
  2. curl_setopt($ch,CURLOPT_POSTFIELDS,'name=John Smith&email_
  3. address=dummy@dummy.com');
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Finally we need to execute the POST and close the connection:
  1. $result = curl_exec($ch);
If you run this script and check in the database you should find another record has been added to our person table in the database:

Check your database after running the code above – you should see that another record has been added by calling your API using cURL

Updating data

Editing the data within our database is achieved in a similar manner. But a web service API makes use of another HTTP method that you may not have come across – the PUT method.

The PUT method is designed to update or replace a file or resource that already exists. Just like before we are going to create a put function in our Person class but this time it requires an ID of the record and their name and email address to be set:
  1. function put($id=NULL, $request_data=NULL) {
  2. if (!is_null($id)&&isset($request_data['name'])&&isset($request_data
  3. ['email_address'])) {
  4. $updateData = array(
  5. 'name' => $request_data['name'],
  6. 'email_address' => $request_data['email_address']
  7. );
  8. $this->db->where('person_id', $id);
  9. if ($results = $this->db->update('person', $updateData))
  10. return array('success' => "Record updated");
  11. }else{
  12. throw new RestException(400,"ID parameter is missing");
  13. }
  14. }
In a similar exercise to the POST example, we invoke this method by utilising the cURL library. This time though we specify the person ID in the URL and add a different option to the cURL call which enables us to PUT data:
  1. curl_setopt($ch, CURLOPT_URL,'http://localhost/index.php/person/2');
  2. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
When you run the code you should see that one of your records has been updated, if you specified an ID in the URL.
  1. curl_setopt($ch, CURLOPT_POSTFIELDS,'id=2&name=Mike Jones&email_address=dummy@dummy.com');

Deleting data

Now you have a new HTTP method under your belt, let’s look at another – the DELETE method. This does exactly what it says on the tin – so let’s create our method, and this time we only need to provide an ID.
  1. function delete($id=NULL) {
  2. if(!is_null($id)){
  3. $this->db->where('person_id', $id);
  4. if ($this->db->delete('person')) return array('success'=>"Record deleted");
  5. }else{
  6. throw new RestException(400,"ID parameter is missing");
  7. }
  8. }
Again, to access this method in the API we need to make use of the cURL library. This time though, set the CURLOPT_CUSTOMREQUEST to DELETE and instead of specifying the variables in CURLOPT_POSTFIELDS, specify them in the URL. This is because many web servers aren’t configured to accept DELETE requests. Your cURL options should look something like this:
  1. curl_setopt($ch, CURLOPT_URL,'http://localhost/index.php/person/2');
  2. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

Here the request to your API has updated the second record that we added – as you can add and edit data your API is now starting to become useful

2 comments:

  1. Thank you for Posting And sharing such great information.can you help me in finding out more detail on final year projects on java.

    ReplyDelete
  2. Nice post it is very useful for all. To know more info. click

    ReplyDelete