How to return Response with custom status code and message as JSON for response body with Slim Framework


#1

Hi,
I’m new with Slim framework. I want to know how to return response with the body and status code as I wish. For now, it only performs as I wish if the query returns records, but not if the query failed (e.g. select * from notexiststable) or returns nothing and with Firefox I see the status is 204 in both cases.

So here’s the code:

$app->get('/models', function (Request $request, Response $response) {
    $conn = getConnection();
    $result = pg_query($conn, "SELECT * FROM model where m_id = 2;");  //this will return 0 record!

    if  (!$result) {
        $data = array("Error Message" => 'Query did not execute successfully');
        $newResponse = $response->withJson($data, 500);
    }
    else {
        if (pg_num_rows($result) == 0) {
            $data = array("Warning Message" => "There's no existent Model!");
            $newResponse = $response->withJson($data, 204);

        }
        else {
            $data = array();
            while ($row = pg_fetch_assoc($result)) {
                $data['Models'][] = $row;               
            }
            $newResponse = $response->withJson($data, 200);
        }
    }

    return $newResponse;

});

Thank you in advanced


#2

@ywy9876 How are you testing a failure?

The only way to get a 500 response if if the model table does not exist in your database and the result of pg_query() in that situation is NULL or false.


#3

Hello,
yes, for testing a failure I changed the table name of the query to a non exist table! But the qiestion is, it will enter the condition if (!$result), but with the codes inside it, I mean, set the body and status code, it seems like it’s not returning anything. I checked it with Firefox, but the status code is 204 no content and I can’t see the message I wish…
Thank you.


#4

If the status is 204, then it isn’t entering this code:

    if  (!$result) {
        $data = array("Error Message" => 'Query did not execute successfully');
        $newResponse = $response->withJson($data, 500);
    }

#5

Oh, 204 is this code:

        if (pg_num_rows($result) == 0) {
            $data = array("Warning Message" => "There's no existent Model!");
            $newResponse = $response->withJson($data, 204);

        }

You won’t get a message with 204. From the spec:

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

For an error response you should use a status code greater than or equal to 400.


#6

Hi,
then I don’t understand why it does not enter the condotion if (!$result) { } if the query failed. The interesting thing is if I put echo ‘some error’ inside this condition and delete the return $newResponse, I can see it with Firefox…