Home > Backend Development > PHP Tutorial > How Do I Access the Response Body in Guzzle HTTP v6 to Retrieve API Tokens?

How Do I Access the Response Body in Guzzle HTTP v6 to Retrieve API Tokens?

Mary-Kate Olsen
Release: 2024-12-02 03:17:13
Original
678 people have browsed it

How Do I Access the Response Body in Guzzle HTTP v6 to Retrieve API Tokens?

How Guzzle HTTP Allows Accessing Response Body in Version 6

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();
Copy after login

Alternatively, the getContents() method of the stream can be used:

$contents = $response->getBody()->getContents();
Copy after login

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'];
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template