vlucas / bulletphp

A resource-oriented micro PHP framework
http://bulletphp.com
BSD 3-Clause "New" or "Revised" License
418 stars 50 forks source link

Use of Bullet with a JSON only api service #47

Closed seblucas closed 10 years ago

seblucas commented 10 years ago

Hi,

First thanks for this framework, I'm using it for a few weeks now and I'm starting to like it a lot ;).

Now my question I want to use Bullet to build an simple Json API (in the same spirit of https://api.github.com). So, even if the request comes from a browser, JSON must always be returned. For now I've added the two format for each paths but I have to admit that hurts a little ;).

Is there a simple way to do that with Bullet ?

I've also had some weird errors trying to use Bullet without any template at all, I'll figure a proper testcase and open another issue.

Thanks again and I'm waiting eagerly for another update.

vlucas commented 10 years ago

You should be able to achieve this by not using the format handlers, and just always returning an array - an array return type will always be sent as JSON automatically by Bullet.

Also, I was actually very recently working on a new feature that lets you set the "default" content type. Right now, bullet uses the first one found in the "Accept" header, and if not present defaults to "html". You can override this directly with something like this, but it doesn't achieve quite the same thing since it doesn't change the default - it just forces every request to be JSON:

// Set every request as JSON manually
$app->on('before', function($request, $response) {
    $request->format('json');
});

You could also register a custom response handler to only respond properly to JSON requests:

$app->registerResponseHandler(
    function($response) {
        return is_array($response->content());
    },
    function($response) use($app) {
        $request = $app->request();
        if($request->format() === 'json') {
            $response->contentType('application/json');
            $response->content(json_encode($response->content()));
        } else {
            $response->status(406);
            $response->content(json_encode(array(
                'error' => 406,
                'message' => "Invalid request format. Accepted format is 'application/json' only."
            )));
        }
    }
);
seblucas commented 10 years ago

Thanks for your answer.

I was indeed on the right track after reading https://github.com/vlucas/bulletphp/pull/9 (should have waited a little before opening this issue). I've used the registerResponseHandler trick.

Thanks a lot for your quick answer.

vlucas commented 10 years ago

Glad I could help! :)