You are viewing the website for BitFrame v1. BitFrame v2.0 was released on 11-May-2020 — new documentation and website will be available soon!


Learn how to return a JSON or JSONP response

Returning JSON

The \BitFrame\Message\ResponseTrait provides a handy withJson() method to return the http response as a JSON/JSONP object. The signature for the method is as follows:

    // the data

    // the http status code
    ?int $status = null, 

    // name of index containing response body; it's
    // only included if key name is not null
    ?string $bodyKeyName = null,

    // callback name for JSONP calls; a response is 
    // returned as JSONP only if callback name is not null
    ?string $jsonpCallback = null,

    // json encoding options
    int $encodingOptions = 0
): ResponseInterface;

Consider the example usage as shown below:

$app->get("/about", function ($request, $response, $next) {
    $data = [
        'page_title' => 'About',
        'page_heading' => 'About BitFrame'

    $response->getBody()->write('Hello World');

    return $response->withJson($data, 200, 'body');

/* output: {
    "page_heading":"About BitFrame",
    "body":"Hello World"
} */

This is a non-PSR standards based method, and is only available on class objects that use \BitFrame\Message\ResponseTrait. Default response objects created in BitFrame have this trait included automatically. The use of this helper method is strictly optional as it's merely meant as a shortcut to what you can just as easily accomplish without using it.


Let us know if you have something to say or add