Skip to content
Advertisement

wp_remote_get and url parameters

I’m trying to use an API with wp_remote_get which requires pagination.

Currently, my WordPress plugin calls the API the following way

$response = wp_remote_get( "https://api.xyz.com/v1/products" ,
      array( 'timeout' => 10,
     'headers' => array( 
        'Authorization' => 'Bearer xyz',
        'accept' => 'application/json',
        'content-type' => 'application/json'
     )
      ));
      $body = wp_remote_retrieve_body( $response );
      return json_decode($body);

Now, if I change the URL from /products to /products?page_size=5&page=2, which works fine in Postman and other programs, i am not getting a response. Why is that? I checked the API documentation of wp_remote_get but am not figuring it out.

Advertisement

Answer

Typically you use curl command to GET the response but I would recommend you to use Guzzle PHP HTTP client to make your calls if you are making multiple of them.

You will have to compser install Guzzle.

composer require guzzlehttp/guzzle:^7.0

I am expecting that the autoloader class is loaded.

Once installed and you can use it as follows.

use GuzzleHttpClient;


$client = new Client(
[
    // Base URI is used with relative requests.
    'base_uri' => https://api.xyz.com/v1/,
    // You can set any number of default request options.
    'timeout'  => 10.0,
    ]
);

$url = 'products';

$payload = array(
    'page_size' => 5,
    'page'      => 2,
);

try {

    $request = $client->request(
        'GET',
        $url,
        [
            'query' => $payload,
        ]
    );

    $status   = $request->getStatusCode();
    $response = json_decode( $request->getBody() );

    if ( 200 === $status ) {
        echo $response;
    }
} catch ( Exception $e ) {
    echo $e;
}

You can change the $url and $payload for other queries.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement