Home > Blockchain >  Get API response URL param using Guzzle HTTP request in Guzzle 7
Get API response URL param using Guzzle HTTP request in Guzzle 7

Time:05-05

I searched online but couldn't find a proper solution. I am calling a Spring service with a POST request using Guzzle Client, The service in case of any errors provides the error message in its URL param like: http://localhost:8085/fedauth/null?errMessage=Mot de passe invalide pour l'utilisateur Karan Sharma.. How can I fetch this param errMessage using Guzzle. Below is my code with Slim in PHP.

  $data = [
    'userName' => base64_encode($userName),
    'userPassword' => base64_encode($userPassword),
    'institution' => $institution,
    'redirectUrl' => $redirectUrl,
    'callerUrl' => $callerUrl,
    'clientId' => $clientId,
    'encryptMode' => $encryptMode,
    'moodleLandPage' => $moodleLandPage,
    'login' => $login,
    'isEncrypted' => true
];


try {

     $apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
   } catch (Exception $exception) {

        return $response->write(json_encode(['error' => $exception->getMessage(),  "auth" => "0" ]));
    }

I have tried using the getEffectiveUrl() method but its no longer supported in Guzzle 7

CodePudding user response:

I guess you get the response as a redirect url? Your question is not clear in that point. In this case you can access it like this:

$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
echo $apiResponse->getEffectiveUrl();

like here: https://docs.guzzlephp.org/en/5.3/http-messages.html#responses

CodePudding user response:

Actually found the answer. You need to add track redirects option as true and then use $response->getHeaderLine('X-Guzzle-Redirect-History'); like below

$client = new GuzzleHttp\Client(['headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded'], 'verify' => false, 'allow_redirects' => ['track_redirects' => true]]);
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
echo $apiResponse->getHeaderLine('X-Guzzle-Redirect-History');
  • Related