Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LaraBABA's avatar

Best way to handle API errors from http request?

Hi all,

I am a bit confused on how to handle this

 $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer xxxxxxxxxxxxxxxxxxxxxxxx'
        ])->post('https://xxxxxx.com', [
            'id' => "add-on",
            'test' => $result,
        ]);

My problem comes with the response. The key fails I get something like this:

{
    "error": {
        "message": "Incorrect API key provided: xxxxxxxxxxxxxxxxxxxxxxxx'. You can find your API key at https://xxxxx.com.",
        "type": "invalid_request_error",
        "param": null,
        "code": "invalid_api_key"
    }
}

But when the key is fine, I get this:

{"id":"COMP-XXXXXXXXXXXXXX","object":"text_OK","created":1657056253,"backup":"123456789"}

As you can see the third party API is not following a similar output on success and fail. How would you then parse this and return an error on a bad key or a success when everything is fine. I tried this (below) but it fails when the key is right, error being "Undefined array key "error" ":

        if($response && $response['error']['code'] === "invalid_api_key"){
            return response()->json(['error' => 'There is a problem with our website, please try again later'], 500);
        }

          return response()->json(['success' => 'success!'], 200);

0 likes
4 replies
tykus's avatar

If it is a well designed API, then the Response should have an appropriate status code; check for it:

 $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer xxxxxxxxxxxxxxxxxxxxxxxx'
        ])->post('https://xxxxxx.com', [
            'id' => "add-on",
            'test' => $result,
        ]);
if (!$response->failed()) {
		// handle the bad response 
}
//  otherwise return the happy path

https://laravel.com/docs/9.x/http-client#making-requests

1 like
Snapey's avatar

what http codes do you get?

1 like
mladen9595's avatar
Level 2

If there is an appropriate status code, I would agree with @tykus.

If not, I think you should modify the if statement to something similar to this:

if(isset($response['error']['code']) && $response['error']['code'] === "invalid_api_key"){
LaraBABA's avatar

@mladen9595 Thanks unfortunately they are not sending a status code :-( I will have to use your solution. Thanks to all.

Please or to participate in this conversation.