An extension to the SLIM framework to implement json API's with great ease.

Last update: May 3, 2022

slim-jsonAPI

Latest Stable Version Total Downloads

This is an extension to the SLIM framework to implement json API's with great ease.

Installation

Using composer you can add use this as your composer.json

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

Usage

To include the middleware and view you just have to load them using the default Slim way. Read more about Slim Here (https://github.com/codeguy/Slim#getting-started)

    require 'vendor/autoload.php';

    $app = new \Slim\Slim();

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

.htaccess sample

Here's an .htaccess sample for simple RESTful API's

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

example method

all your requests will be returning a JSON output. the usage will be $app->render( (int)$HTTP_CODE, (array)$DATA);

example Code

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

example output

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

Errors

To display an error just set the error => true in your data array. All requests will have an error param that defaults to false.

    $app->get('/user/:id', function($id) use ($app) {

        //your code here

        $app->render(404,array(
                'error' => TRUE,
                'msg'   => 'user not found',
            ));
    });
{
    "msg":"user not found",
    "error":true,
    "status":404
}

You can optionally throw exceptions, the middleware will catch all exceptions and display error messages.

    $app->get('/user/:id', function($id) use ($app) {

        //your code here

        if(...){
            throw new Exception("Something wrong with your request!");
        }
    });
{
    "error": true,
    "msg": "ERROR: Something wrong with your request!",
    "status": 500
}

Embedding response data and metadata in separate containers

It is possible to separate response metadata and business information in separate containers.

To make it possible just init JsonApiView with containers names

add(new \JsonApiMiddleware());">
   require 'vendor/autoload.php';

    $app = new \Slim\Slim();

    $app->view(new \JsonApiView("data", "meta"));
    $app->add(new \JsonApiMiddleware());

Response

{
    "data":{
        "msg":"welcome to my API!"
    },
    "meta":{
        "error":false,
        "status":200
    }
}

routing specific requests to the API

If your site is using regular HTML responses and you just want to expose an API point on a specific route, you can use Slim router middlewares to define this.

get('/api','APIrequest',function() use($app){ //this request will have full json responses $app->render(200,array( 'msg' => 'welcome to my API!', )); });">
    function APIrequest(){
        $app = \Slim\Slim::getInstance();
        $app->view(new \JsonApiView());
        $app->add(new \JsonApiMiddleware());
    }


    $app->get('/home',function() use($app){
        //regular html response
        $app->render("template.tpl");
    });

    $app->get('/api','APIrequest',function() use($app){
        //this request will have full json responses

        $app->render(200,array(
                'msg' => 'welcome to my API!',
            ));
    });

middleware

The middleware will set some static routes for default requests. if you dont want to use it, you can copy its content code into your bootstrap file.

IMPORTANT: remember to use $app->config('debug', false); or errors will still be printed in HTML

GitHub

https://github.com/entomb/slim-json-api
Comments
  • 1. JsonApiView accessing undefined objects, method.

    Hi,

    When I call the view object from my own middleware class, the following error is called.

    PHP Fatal error:  Call to a member function getMessages() on a non-object in /Users/ben/www/collateit/mvp/api/vendor/entomb/slim-json-api/jsonAPI/JsonApiView.php on line 42
    

    which relates to this line:

    $flash = $this->data->flash->getMessages();
    

    presumably 'flash' is not an object?

    Cheers Ben

    Reviewed by bensquire at 2013-12-11 14:55
  • 2. ERROR: could not find driver

    I added it to composer to my current slim app, added the Middleware and the view, but now I get this error returned?

    {"error":true,"msg":"ERROR: could not find driver","status":500}

    What gone wrong? Thanks in advance

    Reviewed by markopavlovic at 2013-10-09 12:49
  • 3. Uncaught exception 'Slim\Exception\Stop'

    Hey, thanks for your tidy little API. I just installed it into my app, but I am receiving this error when using the JsonApi middleware + view...

    PHP Fatal error:  Uncaught exception 'Slim\Exception\Stop' in /.../vendor/slim/slim/Slim/Slim.php:1017
    Stack trace:
    #0 /.../vendor/entomb/slim-json-api/jsonAPI/JsonApiView.php(86): Slim\Slim->stop()
    

    I am calling the view render from another middleware's call() function as:

    $this->app->render(401, array(
                    'error' => TRUE,
                    'message' => 'Access denied.'
                    ));
    

    Wondering why this happens and where would be the proper place to catch the exception?

    Reviewed by plong0 at 2015-02-17 20:07
  • 4. Strict Mode errors

    When strict mode is enabled - slim shows such error

    Declaration of JsonApiView::render() should be compatible with Slim\View::render($template, $data = NULL)
    
    Reviewed by nicknill at 2014-03-19 14:07
  • 5. Declaration of JsonApiView::render() should be compatible with Slim\View::render($template, $data = NULL)

    Hello! I have an issue with JsonApiView: Declaration of JsonApiView::render() should be compatible with Slim\View::render($template, $data = NULL)

    Installed via composer. Error appears only if ini_set ('error_reporting', E_ALL);

    Test application:

    ini_set ('error_reporting', E_ALL);
    ini_set ('display_errors', '1');
    
    require 'vendor/autoload.php';
    
    use Slim\Slim;
    use Slim\Middleware;
    use Slim\Views\Twig;
    $app = new Slim([
        'view' => new Twig(),
        'templates.path' => './public',
        'mode' => 'development',
    ]);
    $app->add(new Middleware\ContentTypes());
    function APIrequest() {
        $app = \Slim\Slim::getInstance();
        $app->view(new \JsonApiView());
        $app->add(new \JsonApiMiddleware());
    }
    
    $app->get('/api','APIrequest',function() use($app){
        //this request will have full json responses
    
        $app->render(200,array(
            'msg' => 'welcome to my API!',
        ));
    });
    $app->run();
    
    Reviewed by 0xbadc0de at 2013-12-09 19:50
  • 6. Add flash messages to the response

    $this->data->flash is a Slim flash object, thus json_encode($this->all()) results in { 'flash': {}, ...} instead of the actual messages. This pull request, puts $this->all() into $response, then adds the actual messages ($this->data->flash->getMessages()) to $response['flash'], and json_encodes($response). The result is { 'flash': {'your flash key': 'your flash message', ...} ... }. Now you can use flash messages in your app and return them in the json.

    Reviewed by bignall at 2013-11-26 19:35
  • 7. slim.after.router add header check

    // Handle Empty response body $app->hook('slim.after.router', function () use ($app) { $res = $app->response(); if($res['Content-Type'] != 'application/octet-stream'){ if (strlen($app->response()->body()) == 0) { $app->render(500,array( 'error' => TRUE, 'msg' => 'Empty response', )); } } });

    Reviewed by bdpsoft at 2013-09-05 13:41
  • 8. Slim 3 Class 'Slim\View' and 'Slim\Middleware' not found

    Fatal error: Class 'Slim\View' not found in C:\xampp\htdocs\slim\test\vendor\entomb\slim-json-api\jsonAPI\JsonApiView.php on line 24

    Fatal error: Class 'Slim\Middleware' not found in C:\xampp\htdocs\slim\test\vendor\entomb\slim-json-api\jsonAPI\JsonApiMiddleware.php on line 23

    Reviewed by kriangsak at 2016-02-05 10:23
  • 9. Support custom exception error code as status code

    You don't want to return 500 status on every type of error. This supports a custom status code returned when throwing an exception and defaults to 500 if empty.

    For example:

    throw new \Exception($e->getFullMessage(), 405);
    
    Reviewed by Zyles at 2015-08-17 01:52
  • 10. Add a parameter for HTTP Content-Type

    Hey, I needed to append ";charset=UTF-8" to the content-type header. I propose a public configuration property named ContentType which defaults to application/json, the same value as before. It shouldn't break any compatibility. Cheers !

    Reviewed by romainbessugesmeusy at 2015-01-23 09:39
  • 11. Call the next, not the default

    In the call for the middleware you need to use $this->next->call() so that it continues the chain instead of $this->app->call(). This pull request fixes it.

    Reviewed by bignall at 2013-11-26 16:09
  • 12. Any chance of a new release?

    Hi folks:

    I'm sure I'm not the only one who's trying to implement a JSON API-compliant API using Slim and this (rather excellent) library.

    As part of this spec, the Content-Type header should be set to application/vnd.api+json rather than application/json. There's a patch in the master branch since January which implements this tiny change but there's no release since August last year.

    I've changed the composer.json for my project to require dev-master, but longer-term even a loose association with a release version would be better if possible. Any chance of a release at any stage? Cheers!

    Reviewed by domhnallw at 2015-10-28 15:50
  • 13. Slim 3.0

    With the Slim 3.0 release candidate out, I've tried to get this to work but I'm getting

    Fatal error: Class 'Slim\Middleware' not found in /var/www//vendor/entomb/slim-json-api/jsonAPI/JsonApiMiddleware.php on line 23
    

    There have been some large changes to how middleware works, http://www.slimframework.com/docs/concepts/middleware.html

    Will this package be updated to work with 3.0? I love it and want to keep using it

    Reviewed by gricey432 at 2015-09-24 02:54
  • 14. jsonp

    Please change jsonp "Content-Type" to "application/javascript"

    public $contentTypeJson = 'application/json'; public $contentTypeJsonp = 'application/javascript';

    if($jsonp_callback !== null){ $app->response()->header('Content-Type', $this->contentTypeJsonp); $app->response()->body($jsonp_callback.'('.json_encode($response, $this->encodingOptions).')'); } else { $app->response()->header('Content-Type', $this->contentTypeJson); $app->response()->body(json_encode($response, $this->encodingOptions)); }

    Reviewed by imonly at 2015-07-31 09:15
REST APIs using Slim framework. Implemented all CRUD operations on the MySql database
REST APIs using Slim framework. Implemented all CRUD operations on the MySql database

PHP REST API using slim framework and CRUD operations ?? Hi there, this is a simple REST API built using the Slim framework. And this is for the folks

Jun 1, 2022
This package provides some basic methods to implement a self updating functionality for your Laravel application. Already bundled are some methods to provide a self-update mechanism via Github or some private repository via http.

This package provides some basic methods to implement a self updating functionality for your Laravel 5 application. Already bundled are some methods to provide a self-update mechanism via Github.

Jun 19, 2022
Simple PHP framework that helps you quickly understand and write simple APIs.

Lightweight-PHP-Framework-For-APIs. Simple PHP framework that helps you quickly understand and write simple APIs. Installation Use the package manager

May 31, 2022
Leaf is a PHP framework that helps you create clean, simple but powerful web apps and APIs quickly and easily.
Leaf is a PHP framework that helps you create clean, simple but powerful web apps and APIs quickly and easily.

Leaf is a PHP framework that helps you create clean, simple but powerful web apps and APIs quickly and easily. Leaf introduces a cleaner and much simpler structure to the PHP language while maintaining it's flexibility. With a simple structure and a shallow learning curve, it's an excellent way to rapidly build powerful and high performant web apps and APIs.

Jun 25, 2022
Simple PHP framework that helps you quickly understand and write simple APIs.

Lightweight PHP Framework For Web and APIs PHP framework that helps you write quickly simple but powerful web apps and APIs Installation Use the packa

May 31, 2022
PhpBoot is an easy and powerful PHP framework for building RESTful/Microservices APIs.
PhpBoot is an easy and powerful PHP framework for building RESTful/Microservices APIs.

?? tiny & fast PHP framework for building Microservices/RESTful APIs, with useful features: IOC, Hook, ORM, RPC, Swagger, Annotation, Parameters binding, Validation, etc.

Jun 26, 2022
TrailLamp is a lightweight, easy-to-use Php MVC framework that can be used to build web applications and REST APIs.

TrailLamp Introduction TrailLamp is a lightweight, easy-to-use Php MVC framework that can be used to build web applications and REST APIs. Installatio

Jun 10, 2022
Slim Framework - Prerequisite Checker
Slim Framework - Prerequisite Checker

Slim Framework - Server Configuration Checker Upload the file check.php to your webserver Browse to the file: https://example.com/check.php Check the

Mar 12, 2022
A Slim PHP MVC framework built just for fun!

Aura Framework A Slim PHP MVC framework built just for fun! en: Note: This repository only contains the core code of the Aura framework. If you want t

Dec 16, 2021
Slim Framework skeleton application with MVC Schema

Slim Framework skeleton application with MVC Schema

Apr 29, 2021
This repository contains a library of optional middleware for your Slim Framework application

Slim Framework Middleware This repository contains a library of optional middleware for your Slim Framework application. How to Install Update your co

May 18, 2019
A curated list of awesome tutorials and other resources for the Slim micro framework

Awesome Slim A curated list of awesome tutorials and other resources for the Slim micro framework Table of Contents Essentials Tutorials Packages and

Apr 18, 2022
Slim Framework 3 Skeleton Application + PagSeguro Lib

Slim Framework 3 Skeleton Application + PagSeguro Lib Aplicação simples para geração do Token para pagamentos no PagSeguro (método transparente) e env

Feb 26, 2018
This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library

This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library. It supports minification and caching, also via Asseti

Mar 31, 2020
Juliangut Slim Framework Doctrine handler middleware

Juliangut Slim Framework Doctrine handler middleware Doctrine handler middleware for Slim Framework. Slim3 version Doctrine integration service for Sl

Mar 23, 2021
Plates Template Integration for Slim micro framework 3

Plates Template Integration for Slim micro framework 3 Render your Slim 3 application views using Plates template engine. Install Via Composer $ compo

Feb 5, 2022
My personal blog developed on the Slim Framework

nesbot.com I am making the source code of my personal site available publicly in case it helps anybody. It's developed using the Slim Framework. I am

Apr 7, 2021
Strict PSR-7 implementation used by the Slim Framework

Strict PSR-7 implementation used by the Slim Framework, but you may use it separately with any framework compatible with the PSR-7 standard.

Jun 30, 2022
Slim Framework custom views

Slim Views This repository contains custom View classes for the template frameworks listed below. You can use any of these custom View classes by eith

Feb 21, 2022