Retrieving API Tokens with PHP
You're aiming to create a wrapper for your company's API. To authenticate with the API, you need to extract tokens from the response body of POST requests. Using the popular Guzzle library, you're encountering difficulties accessing the token within the Guzzle response object.
Guzzle PSR-7 Implementation
Guzzle adheres to the PSR-7 standard, which utilizes stream wrappers for response bodies. These stream wrappers, implemented using PHP temp streams, store the response body data.
Accessing Response Body
To obtain the full response body, you can utilize PHP's string casting operator:
$contents = (string) $response->getBody();
Alternatively, the getContents() method of the stream can be used:
$contents = $response->getBody()->getContents();
The primary difference between these approaches lies in the behavior of getContents(), which only returns the remaining contents after the first call. Subsequent calls will return an empty string unless the stream position is adjusted using rewind() or seek().
Example Code
'http://companysub.dev.myapi.com/']); $response = $client->post('api/v1/auth/', [ 'form_params' => [ 'username' => $user, 'password' => $password ] ]); // Convert response body to string and decode JSON $contents = (string) $response->getBody(); $data = json_decode($contents, true); // Extract token $token = $data['data']['token'];
Once the token is obtained, you can proceed to use it for API authentication.
The above is the detailed content of How Do I Access the Response Body in Guzzle HTTP v6 to Retrieve API Tokens?. For more information, please follow other related articles on the PHP Chinese website!