How to Retrieve HTTP Status Code with Guzzle?
Asked Answered
S

2

17

New to Guzzle/Http.

I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.

I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).

This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )

namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;

$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';

try {

    $res = $client->request('POST', $url, [
        'form_params' => [
            'username' => 'abc',
            'password' => '123'                     
        ]
    ]);

} catch (ClientException $e) {

    //echo Psr7\str($e->getRequest());
    echo Psr7\str($e->getResponse());

}
Squeamish answered 2/5, 2018 at 12:53 Comment(0)
B
35

You can use the getStatusCode function.

$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();

Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.

// On client creation
$client = new GuzzleHttp\Client([
  'allow_redirects' => false
]);

// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);

If you want to check status code in catch block, then you need to use $exception->getCode()

Boydboyden answered 10/8, 2018 at 15:33 Comment(0)
S
1

you can also use this code :

    $client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);

hope help you

Sugarcoat answered 7/5, 2018 at 14:47 Comment(2)
Thanks for your answer, Emmanuel! You're answer will be more helpful to others (and more likely to get upvotes) if you provide a short explanation of what your code does and why it will fix the problem.Impurity
Thanks @divibisan! Copy that!Sugarcoat

© 2022 - 2024 — McMap. All rights reserved.