lethalMango
lethalMango

Reputation: 4491

PHP REST API Routing

I have been looking at APIs and developing a REST API for a project that we are working on.

The API only accepts connections from one source in JSON format, I understand that bit fine.

If understand the majority of what is being said, however I don't understand the 3rd code example down and where the routing information would go.

The example they have provided is:

$data = RestUtils::processRequest();

switch($data->getMethod)
{
    case 'get':
        // retrieve a list of users
        break;
    case 'post':
        $user = new User();
        $user->setFirstName($data->getData()->first_name);  // just for example, this should be done cleaner
        // and so on...
        $user->save();
        break;
    // etc, etc, etc...
}

The part I am unsure on is how to accept the original request i.e. /get/user/1 - how do you route that to the correct part of the script.

If there has been another SO question (I have searched for quite some time) or any further educational examples please do point me in the right direction.

Update

I have found a few routing PHP classes out there, but nothing thats just small and does what it says on the tin, everything seems to do routing + 2000 other things on top.

I now have all the classes I need for this project named as I wish to access them from the URI i.e.:

/data/users /data/users/1 /hash/users /hash/users/1 /put/users/1?json={data}

So all of these should use the users class, then one of the data, hash or put methods passing anything additional after that into the method as arguments.

If anyone could just explain how that bit works that would be a huge help!

Thanks :)

Upvotes: 4

Views: 13211

Answers (2)

johnlemon
johnlemon

Reputation: 21449

In your case, you will need a redirect rule that will send the request to something like this index.php?user=id. Then you can process the get request.

The best solution I found for php REST architecture (including routing) is:

http://peej.github.com/tonic/

Upvotes: 0

Easen
Easen

Reputation: 296

From the outset it looks like the website you've pointed out does not include a router or a dispatcher. There are plenty of PHP5 frameworks around which include a route and/or a dispatch or some description. (http://en.wikipedia.org/wiki/Comparison_of_Web_application_frameworks#PHP)

A router would be a class which have a list of predefined routes these could be really basic or quite complex, all depends on want you want to do. A good REST router IMO would look something like this:

:module/:controller/:params

And then the router would then router to the correct action based on the HTTP request (GET, POST, PUT, DELETE, OPTIONS)

public function getAction($id) {
    // Load item $id
}

Upvotes: 1

Related Questions