Creating a RESTful API Using Slim PHP Framework

2014-11-07

Christian Crawford

Creating a RESTful API Using Slim PHP Framework

Tutorial on creating a RESTful API using the Slim PHP micro framework with GET, POST, PUT, DELETE operations.

Restful architectures are often used to create client/server network environments. REST, which stands for representational state transfer, is a simpler alternative to SOAP and WSDL services, but still maintains great features like platform-independence and language independence. REST services explicitly use HTTP methods when implementing their calls, therefore any good API should support the basic GET, POST, PUT, and DELETE methods.

For this article we will be using the slim PHP micro framework to implement the RESTful API. Slim was chosen because it is very light weight, clean, supports all the HTTP methods, and also provides support for middleware layers.

You must begin the PHP script by including the slim libraries:

require 'Slim/Slim.php';

Next you will create a new instance of your app and define the routes that you will be using:

$app = new Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->post('/user', 'addUser');
$app->put('/user/:id', 'updateUser');
$app->delete('/user/:id', 'deleteUser');
$app->run();

Further slim documentation can be found here.