Create a REST API with PHP

One of the latest (sort of) crazes sweeping the net is APIs, more specifically those that leverage REST. It’s really no surprise either, as consuming REST APIs is so incredibly easy… in any language. It’s also incredibly easy to create them as you essentially use nothing more than an HTTP spec that has existed for ages. One of the few things that I give Rails credit for is its well thought-out REST support, both for providing and consuming these APIs (as its been explained by all the Rails fanboys I work with).

Seriously, if you’ve never used REST, but you’ve ever had to work with (or worse, create) a SOAP API, or simply opened a WSDL and had your head explode, boy do I have good news for you!

So, What on Earth is REST? Why Should You Care?

Before we get into writing some code, I want to make sure everyone’s got a good understanding of what REST is and how its great for APIs. First, technically speaking, REST isn’t specific to just APIs, it’s more of a generic concept. However, obviously, for the sake of this article we’ll be talking about it in the context of an API. So, let’s look at the basic needs of an API and how REST addresses them.

All APIs need to accept requests. Typically, with a RESTful API, you’ll have a well-defined URL scheme. Let’s say you want to provide an API for users on your site (I know, I always use the “users” concept for my examples). Well, your URL structure would probably be something like, “api/users” and “api/users/[id]” depending on the type of operation being requested against your API. You also need to consider how you want to accept data. These days a lot of people are using JSON or XML, and I personally prefer JSON because it works well with JavaScript, and PHP has easy functionality for encoding and decoding it. If you wanted your API to be really robust, you could accept both by sniffing out the content-type of the request (i.e. application/json or application/xml), but it’s perfectly acceptable to restrict things to one content type. Heck, you could even use simple key/value pairs if you wanted.

The other piece of a request is what it’s actually meant to do, such as load, save, etc. Normally, you’d have to come up with some sort of architecture that defines what action the requester (consumer) desires, but REST simplifies that. By using HTTP request methods, or verbs, we don’t need to define anything. We can just use the GET, POST, PUT, and DELETE methods, and that covers every request we’d need. You can equate the verbs to your standard crud-style stuff: GET = load/retrieve, POST = create, PUT = update, DELETE = well, delete. It’s important to note that these verbs don’t directly translate to CRUD, but it is a good way to think about them. So, going back to the above URL examples, let’s take a look at what some possible requests could mean:

  • GET request to /api/users – List all users
  • GET request to /api/users/1 – List info for user with ID of 1
  • POST request to /api/users – Create a new user
  • PUT request to /api/users/1 – Update user with ID of 1
  • DELETE request to /api/users/1 – Delete user with ID of 1

As you hopefully see, REST has already taken care of a lot of the major headaches of creating your own API through some simple, well-understood standards and protocols, but there’s one other piece to a good API…

So, REST handles requests very easily, but it also makes generating responses easy. Similar to requests, there are two main components of a RESTful response: the response body, and a status code. The response body is pretty easy to deal with. Like requests, most responses in REST are usually either JSON or XML (perhaps just plain text in the case of POSTs, but we’ll cover that later). And, like requests, the consumer can specify the response type they’d like through another part of the HTTP request spec, “Accept”. If a consumer wishes to receive an XML response, they’d just send an Accept header as a part of their request saying as much (”Accept: application/xml”). Admittedly, this method isn’t as widely adopted (tho it should be), so you have can also use the concept of an extension in the URL. For example, /api/users.xml means the consumer wants XML as a response, similarly /api/users.json means JSON (same for things like /api/users/1.json/xml). Either way you choose (I say do both), you should pick a default response type as a lot of the time people wont’ even tell you what they want. Again, I’d say go with JSON. So, no Accept header or extension (i.e. /api/users) should not fail, it should just fail-over to the default response-type.

But what about errors and other important status messages associated with requests? Easy, use HTTP status codes! This is far and above one of my favorite things about creating RESTful APIs. By using HTTP status codes, you don’t need to come up with a error / success scheme for your API, it’s already done for you. For example, if a consumer POSTS to /api/users and you want to report back a successful creation, simply send a 201 status code (201 = Created). If it failed, send a 500 if it failed on your end (500 = Internal Server Error), or perhaps a 400 if they screwed up (400 = Bad request). Maybe they’re trying to POST against an API endpoint that doesn’t accept posts… send a 501 (Not implemented). Perhaps your MySQL server is down, so your API is temporarily borked… send a 503 (Service unavailable). Hopefully, you get the idea. If you’d like to read up a bit on status codes, check them out on wikipedia: List of HTTP Status Codes.

I’m hoping you see all the advantages you get by leveraging the concepts of REST for your APIs. It really is super-cool, and its a shame its not more widely talked about in the PHP community (at least as far as I can tell). I think this is likely due to the lack of good documentation on how to deal with requests that aren’t GET or POST, namely PUT and DELETE. Admittedly, it is a bit goofy dealing with these, but it certainly isn’t hard. I’m also sure some of the popular frameworks out there probably have some sort of REST implementation, but I’m not a huge framework fan (for a lot of reasons that I won’t get into), and it’s also good to know these things even if somebody’s already created the solution for you.

If you’re still not convinced that this is a useful API paradigm, take a look at what REST has done for Ruby on Rails. One of its major claims to fame is how easy it is to create APIs (through some sort of RoR voodoo, I’m sure), and rightly so. Granted I know very little about RoR, but the fanboys around the office have preached this point to me many times. But, I digress… let’s write some code!

Getting Started with REST and PHP

One last disclaimer: the code we’re about to go over is in no way intended to be used as an example of a robust solution. My main goal here is to show how to deal with the individual components of REST in PHP, and leave creating the final solution up to you.

So, let’s dig in! I think the best way to do something practical is to create a class that will provide all the utility functions we need to create a REST API. We’ll also create a small class for storing our data. You could also then take this, extend it, and apply it to your own needs. So, let’s stub some stuff out:

  1. class RestUtils
  2. {
  3.     public static function processRequest()
  4.     {
  5.     }
  6.     public static function sendResponse($status = 200, $body = ”, $content_type = ‘text/html’)
  7.     {
  8.     }
  9.     public static function getStatusCodeMessage($status)
  10.     {
  11.         // these could be stored in a .ini file and loaded
  12.         // via parse_ini_file()… however, this will suffice
  13.         // for an example
  14.         $codes = Array(
  15.             100 => ‘Continue’,
  16.             101 => ‘Switching Protocols’,
  17.             200 => ‘OK’,
  18.             201 => ‘Created’,
  19.             202 => ‘Accepted’,
  20.             203 => ‘Non-Authoritative Information’,
  21.             204 => ‘No Content’,
  22.             205 => ‘Reset Content’,
  23.             206 => ‘Partial Content’,
  24.             300 => ‘Multiple Choices’,
  25.             301 => ‘Moved Permanently’,
  26.             302 => ‘Found’,
  27.             303 => ‘See Other’,
  28.             304 => ‘Not Modified’,
  29.             305 => ‘Use Proxy’,
  30.             306 => ‘(Unused)’,
  31.             307 => ‘Temporary Redirect’,
  32.             400 => ‘Bad Request’,
  33.             401 => ‘Unauthorized’,
  34.             402 => ‘Payment Required’,
  35.             403 => ‘Forbidden’,
  36.             404 => ‘Not Found’,
  37.             405 => ‘Method Not Allowed’,
  38.             406 => ‘Not Acceptable’,
  39.             407 => ‘Proxy Authentication Required’,
  40.             408 => ‘Request Timeout’,
  41.             409 => ‘Conflict’,
  42.             410 => ‘Gone’,
  43.             411 => ‘Length Required’,
  44.             412 => ‘Precondition Failed’,
  45.             413 => ‘Request Entity Too Large’,
  46.             414 => ‘Request-URI Too Long’,
  47.             415 => ‘Unsupported Media Type’,
  48.             416 => ‘Requested Range Not Satisfiable’,
  49.             417 => ‘Expectation Failed’,
  50.             500 => ‘Internal Server Error’,
  51.             501 => ‘Not Implemented’,
  52.             502 => ‘Bad Gateway’,
  53.             503 => ‘Service Unavailable’,
  54.             504 => ‘Gateway Timeout’,
  55.             505 => ‘HTTP Version Not Supported’
  56.         );
  57.         return (isset($codes[$status])) ? $codes[$status] : ”;
  58.     }
  59. }
  60. class RestRequest
  61. {
  62.     private $request_vars;
  63.     private $data;
  64.     private $http_accept;
  65.     private $method;
  66.     public function __construct()
  67.     {
  68.         $this->request_vars      = array();
  69.         $this->data              = ”;
  70.         $this->http_accept       = (strpos($_SERVER[‘HTTP_ACCEPT’], ‘json’)) ? ‘json’ : ‘xml’;
  71.         $this->method            = ‘get’;
  72.     }
  73.     public function setData($data)
  74.     {
  75.         $this->data = $data;
  76.     }
  77.     public function setMethod($method)
  78.     {
  79.         $this->method = $method;
  80.     }
  81.     public function setRequestVars($request_vars)
  82.     {
  83.         $this->request_vars = $request_vars;
  84.     }
  85.     public function getData()
  86.     {
  87.         return $this->data;
  88.     }
  89.     public function getMethod()
  90.     {
  91.         return $this->method;
  92.     }
  93.     public function getHttpAccept()
  94.     {
  95.         return $this->http_accept;
  96.     }
  97.     public function getRequestVars()
  98.     {
  99.         return $this->request_vars;
  100.     }
  101. }

OK, so what we’ve got is a simple class for storing some information about our request (RestRequest), and a class with some static functions we can use to deal with requests and responses. As you can see, we really only have two functions to write… which is the beauty of this whole thing! Right, let’s move on…

Processing the Request

Processing the request is pretty straight-forward, but this is where we can run into a few catches (namely with PUT and DELETE… mostly PUT). We’ll go over those in a moment, but let’s examine the RestRequest class a bit. If you’ll look at the constructor, you’ll see that we’re already interpreting the HTTP_ACCEPT header, and defaulting to JSON if none is provided. With that out of the way, we need only deal with the incoming data.

There are a few ways we could go about doing this, but let’s just assume that we’ll always get a key/value pair in our request: ‘data’ => actual data. Let’s also assume that the actual data will be JSON. As stated in my previous explanation of REST, you could look at the content-type of the request and deal with either JSON or XML, but let’s keep it simple for now. So, our process request function will end up looking something like this:

  1. public static function processRequest()
  2. {
  3.     // get our verb
  4.     $request_method = strtolower($_SERVER[‘REQUEST_METHOD’]);
  5.     $return_obj     = new RestRequest();
  6.     // we’ll store our data here
  7.     $data           = array();
  8.     switch ($request_method)
  9.     {
  10.         // gets are easy…
  11.         case ‘get’:
  12.             $data = $_GET;
  13.             break;
  14.         // so are posts
  15.         case ‘post’:
  16.             $data = $_POST;
  17.             break;
  18.         // here’s the tricky bit…
  19.         case ‘put’:
  20.             // basically, we read a string from PHP’s special input location,
  21.             // and then parse it out into an array via parse_str… per the PHP docs:
  22.             // Parses str  as if it were the query string passed via a URL and sets
  23.             // variables in the current scope.
  24.             parse_str(file_get_contents(‘php://input’), $put_vars);
  25.             $data = $put_vars;
  26.             break;
  27.     }
  28.     // store the method
  29.     $return_obj->setMethod($request_method);
  30.     // set the raw data, so we can access it if needed (there may be
  31.     // other pieces to your requests)
  32.     $return_obj->setRequestVars($data);
  33.     if(isset($data[‘data’]))
  34.     {
  35.         // translate the JSON to an Object for use however you want
  36.         $return_obj->setData(json_decode($data[‘data’]));
  37.     }
  38.     return $return_obj;
  39. }

Like I said, pretty straight-forward. However, a few things to note… First, you typically don’t accept data for DELETE requests, so we don’t have a case for them in the switch. Second, you’ll notice that we store both the request variables, and the parsed JSON data. This is useful as you may have other stuff as a part of your request (say an API key or something) that isn’t truly the data itself (like a new user’s name, email, etc.).

So, how would we use this? Let’s go back to the user example. Assuming you’ve routed your request to the correct controller for users, we could have some code like this:

  1. $data = RestUtils::processRequest();
  2. switch($data->getMethod)
  3. {
  4.     case ‘get’:
  5.         // retrieve a list of users
  6.         break;
  7.     case ‘post’:
  8.         $user = new User();
  9.         $user->setFirstName($data->getData()->first_name);  // just for example, this should be done cleaner
  10.         // and so on…
  11.         $user->save();
  12.         break;
  13.     // etc, etc, etc…
  14. }

Please don’t do this in a real app, this is just a quick-and-dirty example. You’d want to wrap this up in a nice control structure with everything abstracted properly, but this should help you get an idea of how to use this stuff. But I digress, let’s move on to sending a response.

Sending the Response

Now that we can interpret the request, let’s move on to sending the response. We already know that all we really need to do is send the correct status code, and maybe some body (if this were a GET request, for example), but there is an important catch to responses that have no body. Say somebody made a request against our sample user API for a user that doesn’t exist (i.e. api/user/123). The appropriate status code to send is a 404 in this case, but simply sending the status code in the headers isn’t enough. If you viewed that page in your web browser, you would get a blank screen. This is because Apache (or whatever your web server runs on) isn’t sending the status code, so there’s no status page. We’ll need to take this into account when we build out our function. Keeping all that in mind, here’s what the code should look like:

  1. public static function sendResponse($status = 200, $body = ”, $content_type = ‘text/html’)
  2. {
  3.     $status_header = ‘HTTP/1.1 ‘ . $status . ‘ ‘ . RestUtils::getStatusCodeMessage($status);
  4.     // set the status
  5.     header($status_header);
  6.     // set the content type
  7.     header(‘Content-type: ‘ . $content_type);
  8.     // pages with body are easy
  9.     if($body != ”)
  10.     {
  11.         // send the body
  12.         echo $body;
  13.         exit;
  14.     }
  15.     // we need to create the body if none is passed
  16.     else
  17.     {
  18.         // create some body messages
  19.         $message = ”;
  20.         // this is purely optional, but makes the pages a little nicer to read
  21.         // for your users.  Since you won’t likely send a lot of different status codes,
  22.         // this also shouldn’t be too ponderous to maintain
  23.         switch($status)
  24.         {
  25.             case 401:
  26.                 $message = ‘You must be authorized to view this page.’;
  27.                 break;
  28.             case 404:
  29.                 $message = ‘The requested URL ‘ . $_SERVER[‘REQUEST_URI’] . ‘ was not found.’;
  30.                 break;
  31.             case 500:
  32.                 $message = ‘The server encountered an error processing your request.’;
  33.                 break;
  34.             case 501:
  35.                 $message = ‘The requested method is not implemented.’;
  36.                 break;
  37.         }
  38.         // servers don’t always have a signature turned on (this is an apache directive “ServerSignature On”)
  39.         $signature = ($_SERVER[‘SERVER_SIGNATURE’] == ”) ? $_SERVER[‘SERVER_SOFTWARE’] . ‘ Server at ‘ . $_SERVER[‘SERVER_NAME’] . ‘ Port ‘ . $_SERVER[‘SERVER_PORT’] : $_SERVER[‘SERVER_SIGNATURE’];
  40.         // this should be templatized in a real-world solution
  41.         $body = ‘<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “”&gt;
  42.                     <html>
  43.                         <head>
  44.                             <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
  45.                             <title>’ . $status . ‘ ‘ . RestUtils::getStatusCodeMessage($status) . ‘</title>
  46.                         </head>
  47.                         <body>
  48.                             <h1>’ . RestUtils::getStatusCodeMessage($status) . ‘</h1>
  49.                             <p>’ . $message . ‘</p>
  50.                             <hr />
  51.                             <address>’ . $signature . ‘</address>
  52.                         </body>
  53.                     </html>’;
  54.         echo $body;
  55.         exit;
  56.     }
  57. }

That’s It! We technically have everything we need now to process requests and send responses. Let’s talk a bit more about why we need to have a standard body response or a custom one. For GET requests, this is pretty obvious, we need to send XML / JSON content instead of a status page (provided the request was valid). However, there’s also POSTs to deal with. Inside of your apps, when you create a new entity, you probably fetch the new entity’s ID via something like mysql_insert_id(). Well, if a user posts to your API, they’ll probably want that new ID as well. What I’ll usually do in this case is simply send the new ID as the body (with a 201 status code), but you could also wrap that in XML or JSON if you’d like.

So, let’s extend our sample implementation a bit:

  1. switch($data->getMethod)
  2. {
  3.     // this is a request for all users, not one in particular
  4.     case ‘get’:
  5.         $user_list = getUserList(); // assume this returns an array
  6.         if($data->getHttpAccept == ‘json’)
  7.         {
  8.             RestUtils::sendResponse(200, json_encode($user_list), ‘application/json’);
  9.         }
  10.         else if ($data->getHttpAccept == ‘xml’)
  11.         {
  12.             // using the XML_SERIALIZER Pear Package
  13.             $options = array
  14.             (
  15.                 ‘indent’ => ‘     ‘,
  16.                 ‘addDecl’ => false,
  17.                 ‘rootName’ => $fc->getAction(),
  18.                 XML_SERIALIZER_OPTION_RETURN_RESULT => true
  19.             );
  20.             $serializer = new XML_Serializer($options);
  21.             RestUtils::sendResponse(200, $serializer->serialize($user_list), ‘application/xml’);
  22.         }
  23.         break;
  24.     // new user create
  25.     case ‘post’:
  26.         $user = new User();
  27.         $user->setFirstName($data->getData()->first_name);  // just for example, this should be done cleaner
  28.         // and so on…
  29.         $user->save();
  30.         // just send the new ID as the body
  31.         RestUtils::sendResponse(201, $user->getId());
  32.         break;
  33. }

Again, this is just an example, but it does show off (I think, at least) how little effort it takes to implement RESTful stuff.

Wrapping Up

So, that’s about it. I’m pretty confident that I’ve beaten the point that this should be quite easy into the ground, so I’d like to close with how you can take this stuff further and perhaps properly implement it.

In a real-world MVC application, what you would probably want to do is set up a controller for your API that loads individual API controllers. For example, using the above stuff, we’d possibly create a UserRestController which had four methods: get(), put(), post(), and delete(). The API controller would look at the request and determine which method to invoke on that controller. That method would then use the utils to process the request, do what it needs to do data-wise, then use the utils to send a response.

You could also take it a step further than that, and abstract out your API controller and data models a bit more. Rather than explicitly creating a controller for every data model in your app, you could add some logic into your API controller to first look for an explicitly defined controller, and if none is found, try to look for an existing model. For example, the url “api/user/1″, would first trigger a lookup for a “user” rest controller. If none is found, it could then look for a model called “user” in your app. If one is found, you could write up a bit of automated voodoo to automatically process all the requests against those models.

Going even further, you could then make a generic “list-all” method that works similar to the previous paragraph’s example. Say your url was “api/users”. The API controller could first check for a “users” rest controller, and if none was found, recognize that users is pluaralized, depluralize it, and then look for a “user” model. If one’s found, load a list the list of users and send that off.

Finally, you could add digest authentication to your API quite easily as well. Say you only wanted properly authenticated users to access your API, well, you could throw some code like this into your process request functionality (borrowed from an existing app of mine, so there’s some constants and variables referenced that aren’t defined in this snippet):

  1. // figure out if we need to challenge the user
  2. if(emptyempty($_SERVER[‘PHP_AUTH_DIGEST’]))
  3. {
  4.     header(‘HTTP/1.1 401 Unauthorized’);
  5.     header(‘WWW-Authenticate: Digest realm=”‘ . AUTH_REALM . ‘”,qop=”auth”,nonce=”‘ . uniqid() . ‘”,opaque=”‘ . md5(AUTH_REALM) . ‘”‘);
  6.     // show the error if they hit cancel
  7.     die(RestControllerLib::error(401, true));
  8. }
  9. // now, analayze the PHP_AUTH_DIGEST var
  10. if(!($data = http_digest_parse($_SERVER[‘PHP_AUTH_DIGEST’])) || $auth_username != $data[‘username’])
  11. {
  12.     // show the error due to bad auth
  13.     die(RestUtils::sendResponse(401));
  14. }
  15. // so far, everything’s good, let’s now check the response a bit more…
  16. $A1 = md5($data[‘username’] . ‘:’ . AUTH_REALM . ‘:’ . $auth_pass);
  17. $A2 = md5($_SERVER[‘REQUEST_METHOD’] . ‘:’ . $data[‘uri’]);
  18. $valid_response = md5($A1 . ‘:’ . $data[‘nonce’] . ‘:’ . $data[‘nc’] . ‘:’ . $data[‘cnonce’] . ‘:’ . $data[‘qop’] . ‘:’ . $A2);
  19. // last check..
  20. if($data[‘response’] != $valid_response)
  21. {
  22.     die(RestUtils::sendResponse(401));
  23. }

Pretty cool stuff, huh? With a little bit of code and some clever logic, you can add a fully functional REST API to your apps very quickly. I’m not just saying that to cheerlead the concept either, I implemented this stuff into one of my personal frameworks in about half a day, and then spent another half day adding all sorts of cool magic to it. If you (the reader) are interested in seeing my final implementation, drop me a note in the comments and I’d be happy to share it with you! Also, if you’ve got any cool ideas you’d like to share, be sure to drop those in the comments as well… if I like it enough, I’d even let you guest author your own article on the subject!

Until next time…

Copy from source:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s