Skip to content
Advertisement

Response to json Payload in POST API not in Json Format

I have a Rest API that accepts a Json Payload, i format the Data and import this into the SQL Database. However when the payload is received the sender is waiting for a response.

They do not want a Typical HTTP 200 OK, they want a formatted Json Response with the Price etc for the submission.

Whenever i output the response to the body, it does not appear to be formatted as a Json and appears as a string, this is causing errors with the flow of the program.

i wanted to check the formatting is correct and the method.

ignoring all the handler and authorization i am typically picking up the payload via:

$payload = (file_get_contents('php://input')); 

do what i need to do with the data then respond as follow:

(of course this is wrapped in a statement of handlers but the successful segment of the code)

http_response_code(200);
$data = array(
"sub_total" => 1000,
"ExtraeChargeTotal" => 0,
"Vat" => 0,
"Total" => 1000
);
$response = json_encode($data);
echo $response  ;

is this the correct way to respond? everything works how i think it should, an appears to work in postman. however the response is a string and not in Json

Advertisement

Answer

To resume the comments, when json datas must been sent with PHP, it’s important to force the Content-Type header by this way :

header('Content-Type: application/json; charset=utf-8');

After the header, send the datas with echo.

For exemple in this case :

http_response_code(200);
$data = array(
"sub_total" => 1000,
"ExtraeChargeTotal" => 0,
"Vat" => 0,
"Total" => 1000
);
if($response = json_encode($data)){
   header('Content-Type: application/json; charset=utf-8');
   echo $response  ;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement