Create your own API with Restler
By 1 comment
on | - Knowledge needed: Intermediate PHP, basic MySQL
- Requires: PHP 5.3 or greater with cURL enabled, MySQL database
- Project time: 4-6 hours
- Download source files
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:- class Say {
- function hello($to='world') {
- return "Hello $to!";
- }
- }
- require_once '../vendor/restler.php';
- use Luracast\Restler\Restler;
- use Luracast\Restler\Defaults;
- Defaults::$smartAutoRouting = false;
- $r = new Restler();
- $r->addAPIClass('Say');
- $r->handle();
index.php/say/hello/Richard AskewBingo – 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.
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.
- use Luracast\Restler\RestException;
- class Person {
- protected $db;
- function __construct(){
- $this->db = newMysqlDb('host', 'username', 'password', 'database');
- }
- function get($id=NULL) {
- if($id != NULL){
- $this->db->where('person_id', $id);
- }
- $results = $this->db->get('person');
- return $results;
- }
- }
- require_once '../vendor/restler.php';
- use Luracast\Restler\Defaults;
- Defaults::$smartAutoRouting = false;
- $r = new Restler();
- $r->addAPIClass(‘Person’);
- $r->handle();
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
- function get($id = NULL)
- {
- if($id != NULL){
- $this->db->where('person_id', $id);
- }
- $results = $this->db->get('person');
- throw new RestException(400, "This ID doesn't exist");
- }
- return $results;
- }
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:- $r->setSupportedFormats('XmlFormat','JsonFormat');
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.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:
- address=dummy@dummy.com');
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:
- function put($id=NULL, $request_data=NULL) {
- ['email_address'])) {
- 'name' => $request_data['name'],
- 'email_address' => $request_data['email_address']
- );
- $this->db->where('person_id', $id);
- if ($results = $this->db->update('person', $updateData))
- }else{
- throw new RestException(400,"ID parameter is missing");
- }
- }
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.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:
Thank you for Posting And sharing such great information.can you help me in finding out more detail on final year projects on java.
ReplyDeleteNice post it is very useful for all. To know more info. click
ReplyDelete