otcphg
Last Updated: September 15, 2016
·
31.88K
· entomb
Jonathan tavares

Create a JSON RESTfull API using Slim framework

Using Slim you can create easy RESTfull websites and API's in seconds, using the simplest and fastest PHP framework.

If you want to create a JSON API in seconds, I've create a Slim extension to handdle json output.

https://github.com/entomb/slim-json-api

1) set up a composer.json file

{
    "require": {
        "slim/slim": "2.*",
        "entomb/slim-json-api": "dev-master"
    }
}

2) use $ composer install to fetch all the code. if you need help check this site: http://getcomposer.org/

3) create a index.php file loading and setting up Slim

require 'vendor/autoload.php';

$app = new \Slim\Slim();

$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());

4) start codding your API using $app->render(CODE, $DATA) to output information.

$app->get('/', function() use ($app) {
    $app->render(200,array(
            'msg' => 'Welcome to my json API!',
        ));
});

Result:
GET /

{
   "msg":"Welcome to my json API!",
   "error":false,
   "status":200
}

5 Responses
Add your response

6554

I'm currently using Tonic by peej.

https://github.com/peej/tonic

Currenlty my only issue is that, to handle url like:
/items/:idParam
or
/items/
or
/items/count
i need to implement 3 different classes.

Anyway, RESTful it's awesome, fast and clean... love it!

over 1 year ago ·
6556
Jonathan tavares

With slim there are ways of creating optional parameters, that example would result in a route like this: /items(/:idParam)(/count)

I realy find Slim the most elegant PHP "router" (wouldn't really call it a framework).

Cheers!,

over 1 year ago ·
7021
13ed268ca670064bf9972ad533d28584

Slim is a really cool router for PHP - but PHP is not a really cool and fast programming language, especially not for APIs because they need to be fast.

I prefer Node.js with the Express framework, which is providing the same functionality in mostly the same syntax but in really fast.

over 1 year ago ·
7027

A few comments. We have created lots of API's both with Node.js and Express, but also in PHP with Slim.

Slim is nice for building RESTful JSON API's. I find Slim paired with an ORM makes for an awesome tool kit for coding API's quickly. Also I would take out the "status":200 and use HTTP Headers to make it true REST.

Great tip though, more people should check out Slim.

over 1 year ago ·
17028
None

You should say about this line also:

$app->run();

As a beginner it wasted my 2hours.

over 1 year ago ·