I'm setting up Guzzle as my Laravel 6's HTTP Client in my project. It was perfectly working and giving responses on every API hit. But suddenly it returns "Call to a member function getStatusCode() on null" error.
I've tried using Postman and curl to hit the API, and they return the right response when Guzzle not.
Instead of returning response, the print_r for RequestException response's return null.
I've tried to debug the REST API to test where the request go when hitting it using Guzzle, and the request didn't even hit to the destination function.
Here's my Guzzle code:
class ApiCallback
{
public static function request($method, $uri, $params = [], $useAccessToken = true){
$client = new \GuzzleHttp\Client();
$response = null;
$jsonObj = null;
try{
if($useAccessToken){
$response = $client->request(
strtoupper($method),
$uri,
[
"headers" =>[
'Accept' => '*/*',
"Authorization" => "Bearer ".Session::get('access_token'),
'Content-Type' => 'application/json',
'User-Agent' => 'saranaku-'.Session::get('id'),
'Content-Length' => '0',
'Accept-Encoding' => 'gzip, deflate, br',
'Connection' => 'keep-alive'
]
,
"body" => \json_encode(
$params
)
]
);
}else{
$response = $client->request(
strtoupper($method),
$uri,
[
"headers" =>[
'Accept' => '*/*',
'Content-Type' => 'application/json',
'User-Agent' => "saranaku-guest",
'Content-Length' => '0',
'Accept-Encoding' => 'gzip, deflate, br',
'Connection' => 'keep-alive'
]
,
"body" => \json_encode(
$params
)
]
);
}
$jsonObj = json_decode((string) $response->getBody());
return new BaseResponse(
$jsonObj->status ?? false,
$jsonObj->code ?? null,
$jsonObj->message ?? null ,
$jsonObj->data ?? null
);
}catch(RequestException $e){
// echo Psr7\str($e->getRequest());
// echo Psr7\str($e->getResponse());
$jsonObj = $e->getResponse();
print_r($e->getResponse());
}
return new BaseResponse(
$jsonObj->status ?? false,
$jsonObj->getStatusCode() ?? null,
$jsonObj->getReasonPhrase() ?? null ,
$jsonObj->data ?? null
);
}
public static function requestWithoutAccessToken($method, $url, $params = []){
return ApiCallback::request($method, $url, $params, false);
}
}
final class BaseResponse
{
public $status;
public $code;
public $message;
public $data;
public function __construct($status,$code,$message = "",$data = [])
{
$this->status = $status;
$this->code = $code;
$this->message = $message;
$this->data = $data;
}
}
Additional information:
{
"data":{
"username": "username_string",
"password": "password_string"
}
}
composer dump-autoload
and the problem still persistsI found the problem and the solution.
So I'm doing some Logging on the exception with Log
and found out that my $uri
is not valid due my API BASE URL was not found on .env
file. So the solution is doing php artisan cache:clear
and the guzzle works.
For anyone who reading this question, please remember to try Log
if the stack trace didn't help you out.