Quickly Build RESTful APIs in PHP with Slim

Writing and interacting with APIs, RESTful APIs in particular, is something most web developers have to deal with. There are a number of ways to implement them, and many of them are quite straightforward, like on the Java side of the things with JAX-RS. With PHP, one of the best options is the Slim Framework.

Slim is actually a PHP micro framework that can be used for far more than just writing RESTful APIs. Digging into the documentation reveals that there is some very powerful routing functionality in there, especially with the slick middleware functionality.

Creating the basis of your RESTful services with Slim is almost embarrassingly easy:

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

// GET route
$app->get('/', function () {
    echo 'This is a GET route';
});

// POST route
$app->post('/', function () {
    echo 'This is a POST route';
});

// PUT route
$app->put('/', function () {
    echo 'This is a PUT route';
});

// DELETE route
$app->delete('/', function () {
    echo 'This is a DELETE route';
});

$app->run();

With that small bit of code, Get, Post, Put, and Delete are now all functional and ready to be utilized. Obviously they need to be wired up to do something useful, but still, it’s refreshing to have something so simple provide so much functionality. If you wanted to separate out the functions from the route setup, and not use anonymous functions, that’s also very easy:

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/:id', 'getItem');
$app->post('/', 'postItem');
$app->put('/:id', 'putItem');
$app->delete('/:id', 'deleteItem');

$app->run();

function getItem($id) {
     // return item $id
}

function postItem() {          
     // save new item
}

function putItem($id) {          
     // update item
}

function deleteItem($id) {          
     // delete item $id
}

There is a lot more to the Slim Framework; I’ve only scratched the surface here, but it is definitely a great codebase to use when implementing a RESTful API in PHP.

Update 2013/1/13: I’ve added a second post, expanding on this topic.

This entry was posted in PHP, Web Development and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *