Laravel HTTP Client send headers, params, raw body as json does not work

Viewed 3198

I want to call an api and I have some headers, path variables and a json raw body to send over post method. First I tried this:

$response = Http::withHeaders([
    'Api-Key' => env('CLIENT_API_KEY'),
])
->post(env('API_ROOT_URL').'/my/api/url/'.$path_variable, [
    'raw_body_0' => $raw_0,
    'raw_body_1' => $raw_1,
]);

And

$response = Http::withHeaders([
    'Api-Key' => env('CLIENT_API_KEY'),
])
->post(env('API_ROOT_URL').'/my/api/url', [
    'path_variable' => $path_variable,
    'raw_body_0' => $raw_0,
    'raw_body_1' => $raw_1,
]);

And $response->successful() return false. Next tried:

$response = Http::withHeaders([
    'Api-Key' => env('CLIENT_API_KEY'),
])
->withBody(json_encode([
    'raw_body_0' => $raw_0,
    'raw_body_1' => $raw_1,
]), 'json')
->post(env('API_ROOT_URL').'/my/api/url/'.$path_variable);

And

$response = Http::withHeaders([
    'Api-Key' => env('CLIENT_API_KEY'),
])
->withBody(json_encode([
    'raw_body_0' => $raw_0,
    'raw_body_1' => $raw_1,
]), 'json')
->post(env('API_ROOT_URL').'/my/api/url', [
    'path_variable' => $path_variable,
]);

And again no success.

NOTE that env('CLIENT_API_KEY') and env('API_ROOT_URL') work great with simple requests with no raw body or with no combination of parameters that I should send. my api is over HTTPS which again works great with other requests. I also tried header 'Content-Type' => 'application/json' and when I send the request with postman, it works fine.

What's the problem? How can I do this?

1 Answers

Try this,

$response = Http::withHeaders([
   'Api-Key' => env('CLIENT_API_KEY'),
])
->send('POST', env('API_ROOT_URL') . '/my/api/url/' . $path_variable, [
   'body' => '{
                "raw_body_0":"' . $raw_0 . '",
                "raw_body_1":"' . $raw_1 . '",
              }'
])->json();

or this one,

$response = Http::withHeaders([
   'Api-Key' => env('CLIENT_API_KEY'),
])
->send('POST', env('API_ROOT_URL') . '/my/api/url/' . $path_variable, [
   'body' => json_encode([
                'raw_body_0' => $raw_0,
                'raw_body_1' => $raw_1,
            ])
])->json();
Related