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());

}

2 Answers 2

36

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()

Sign up to request clarification or add additional context in comments.

Comments

1

you can also use this code :

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

hope help you

2 Comments

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.
Thanks @divibisan! Copy that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.