Complete API with OAuth2, JWT and Rate limiting

Welcome Phalcon community!

I've just finished a little API skeleton which I'll use for my next project, and decided to share it with you as I don't find anything like it ready to use.

Phalcon2Rest

This will be my first Phalcon project, so while developing this skeleton pretty much I learned the basics of Phalcon. If you see something wrong, or have some ideas, let me know ;)

Impressive benchmark using file cache, sqlite3 database and no optimizations at all on my desktop machine:

Document Path:          /v1/example
Document Length:        374 bytes

Concurrency Level:      100
Time taken for tests:   2.814 seconds
Complete requests:      2000
Failed requests:        0
Total transferred:      1298096 bytes
HTML transferred:       718096 bytes
Requests per second:    710.78 [#/sec] (mean)
Time per request:       140.690 [ms] (mean)
Time per request:       1.407 [ms] (mean, across all concurrent requests)
Transfer rate:          450.52 [Kbytes/sec] received

Cheers



11.8k

awesome thanks

edited May '16

For the start,

instead of:

    $app->before(function () use ($app, $di){
    $config = $di->getShared('config');
    }

you can do just this (w/o injecting DI):

    $app->before(function () use ($app){
    $config = $app->config; //config service is already present in your $app
    }

it's better to use Framework's methods than raw:

    //instead two lines
    $in = file_get_contents('php://input');
    $in = json_decode($in, FALSE);
    // much preferred one liner:
    $in = trim($app->request->getJsonRawBody());

Instead of using __construct(), it's better to use Phalcon's onConstruct() method.


    /**
     * Constructor, calls the parse method for the query string by default.
     * @param boolean $parseQueryString true Can be set to false if a controller needs to be called
     *        from a different controller, bypassing the $allowedFields parse
     */
    public function __construct($parseQueryString = true) {
        parent::__construct();
        if ($parseQueryString){
            $this->parseRequest($this->allowedFields);
        }
        return;
    }

https://docs.phalconphp.com/en/latest/reference/controllers.html#initializing-controllers

edited May '16

@stamster: Thank you for the time to inspect my code. I've included the modifications above as well as the missing two grants provided by the OAuth2 server (implicit & auth code).

I believe that having one good prototype project like this will attract more developers to start using Phalcon, as most of this stuff is provided out-of-the-box with all modern frameworks.

You're welcome! That was very quick look. When I have more time, I'll check in detail.

Overall, thumbs up for your choice to use JWT and rate limiting for your API!

Thanks for sharing and thanks for willing to support PhalconPHP!