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

Overview

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

Comments
  • JsonApiView accessing undefined objects, method.

    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

    opened by bensquire 9
  • ERROR: could not find driver

    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

    opened by markopavlovic 6
  • Uncaught exception 'Slim\Exception\Stop'

    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?

    opened by plong0 3
  • Strict Mode errors

    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)
    
    opened by nicknill 3
  • Declaration of JsonApiView::render() should be compatible with Slim\View::render($template, $data = NULL)

    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();
    
    opened by 0xbadc0de 3
  • Add flash messages to the response

    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.

    opened by bignall 3
  • slim.after.router add header check

    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', )); } } });

    opened by bdpsoft 3
  • Slim 3   Class 'Slim\View' and 'Slim\Middleware' not found

    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

    opened by kriangsak 2
  • Support custom exception error code as status code

    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);
    
    opened by Zyles 2
  • Add a parameter for HTTP Content-Type

    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 !

    opened by romainbessugesmeusy 2
  • Call the next, not the default

    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.

    opened by bignall 2
  • Any chance of a new release?

    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!

    opened by domhnallw 4
  • Slim 3.0

    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

    opened by gricey432 8
  • jsonp

    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)); }

    opened by imonly 0
Releases(1.2.3)
Owner
Jonathan Tavares
Add a bio
Jonathan Tavares
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

Hanoak 2 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.

Holger Lösken 311 Dec 31, 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

Youssef Hajjari 24 Jul 22, 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 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.

Leaf Framework 706 Jan 3, 2023
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

Youssef Hajjari 24 Jul 22, 2022
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.

tknet 656 Jan 4, 2023
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

Etorojah Okon 14 Jun 10, 2022
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

Daniel Opitz 6 Aug 30, 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

Murilo Magalhães Barreto 2 Dec 16, 2021
Slim Framework skeleton application with MVC Schema

Slim Framework skeleton application with MVC Schema

JingwenTian 9 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

Slim Framework 47 Nov 7, 2022
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

Sawyer Charles 466 Dec 8, 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

Raí Siqueira 1 Feb 26, 2018
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

Brian Nesbitt 56 Sep 14, 2022
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

Projek XYZ 26 Feb 5, 2022
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

Julián Gutiérrez 6 Mar 23, 2021
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

Gerard Sychay 22 Mar 31, 2020
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.

Slim Framework 96 Nov 14, 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

Slim Framework 302 Feb 21, 2022