dan3460's avatar

Return a dummy json

I have a post to an API that return a Json.

   function postOrder(string $body): Json
    {
        return Http::withHeaders($this->headers)
            ->post($this->baseSite1 . 'onlineorders', $body)
            ->json();
    }

As i don't want to post to the API i want to send the response that i would get from the API. I can probably json_decode($myString) and then return the json_decode($newArray), but seems dumb. Is there a way to return a json object from the string?

0 likes
3 replies
tisuchi's avatar

@dan3460 How about this?


function postOrder(string $body): \Illuminate\Http\JsonResponse
{
    // Dummy response array that simulates the API response
    $dummyResponse = [
        'order_id' => 12345,
        'status' => 'success',
        'message' => 'Order has been created successfully',
        'data' => [
            'product' => 'Sample Product',
            'quantity' => 2,
            'price' => 49.99
        ]
    ];

    // Return the dummy response as a JSON object
    return response()->json($dummyResponse);
}

dan3460's avatar

Thanks for the answer, but i was traying to use the response that i get from Postman. Which is something like this:

{"httpStatusCode":400,"message":"Bad Request","validationErrors":[{"fieldName":"","code":"CUSTOMER_LOCATION_NOT_FOUND","message":"Invalid CustomerLocation Id"}],"traceIdentifier":"fcc5223695390ff936e0334a3aa1daba"}

i thought that doing something like this would work, but i get an error saying that the returned type is not Json:

$a = json_decode('... the response from Postman...');
return json_encode($a);
JussiMannisto's avatar

What is the Json type that your method is hinting as the return type? Typically you'd return either \Illuminate\Http\JsonResponse or \Illuminate\Http\Response.

If you want to return a JSON string as is, you just need to set the Content-Type header:

return response($jsonString)->header('Content-Type', ['application/json']);

The return type there is Response. If you have decoded the JSON string into a PHP array, you can use response()->json():

$a = json_decode('... the response from Postman...');
return response()->json($a);

That automatically sets the Content-Type to application/json, and serializes the array into a JSON string. The return type is JsonResponse.

Please or to participate in this conversation.