The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

How to preapre a json response on a proper way

Andrew's Avatar

Andrew

05 Jan, 2016 05:07 PM

Hello,

I try to make a simple REST API but faced a problem. I do not know how to set response as json. I've tried the below:

$app->get('/shelf/create', function ($request, $response, $args) {
    $response = $response->withHeader('Content-Type', 'application/json');
    echo json_encode([123]);
});

Unfortunatelly it sends the content as an HTML.

Cheers,
Andrew

  1. 1 Posted by Rob Allen on 05 Jan, 2016 05:16 PM

    Rob Allen's Avatar

    You need to return the $response.

    There's a useful Slim helper method though:

    $app->get('/shelf/create', function ($request, $response, $args) { 
        return $response->withJson([123]);
    });
    
  2. 2 Posted by Andrew on 05 Jan, 2016 05:28 PM

    Andrew's Avatar

    Fantastic! Thanks.

    BTW. Why doesn't withHeader() method replace the Content-Type as I've set? Is it a normal behavior?

  3. 3 Posted by Andrew on 05 Jan, 2016 05:31 PM

    Andrew's Avatar

    I am talking about the case as below:

    $app->get('/shelf/create', function ($request, $response, $args) {
        $response = $response->withHeader('Content-Type', 'application/json');
        $body = $response->getBody();
        // don't look at this line, it's only to show the way to output the response
        $body->write('Hello');
    });

  4. 4 Posted by Rob Allen on 05 Jan, 2016 05:33 PM

    Rob Allen's Avatar

    You have to return the $response.

    $app->get('/shelf/create', function ($request, $response, $args) { 
        $response = $response->withHeader('Content-Type', 'application/json'); 
        $body = $response->getBody(); 
        // don't look at this line, it's only to show the way to output the response 
        $body->write('Hello'); 
        return $response;
    });
    
  5. 5 Posted by Andrew on 05 Jan, 2016 05:40 PM

    Andrew's Avatar

    Thanks Rob! Everything is clear right now.

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac