2

I'm writing a WordPress plugin and want to retrieve data from my API on another domain using wp_remote_get()

On this page: https://wp-kama.com/function/wp_remote_get

There is a Usage Template:

$remote_get = wp_remote_get( $url, array(
    'timeout'     => 5,
    'redirection' => 5,
    'httpversion' => '1.0',
    'user-agent'  => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ),
    'blocking'    => true,
    'headers'     => array(),
    'cookies'     => array(),
    'body'        => null,
    'compress'    => false,
    'decompress'  => true,
    'sslverify'   => true,
    'stream'      => false,
    'filename'    => null
) );

The default for the 'body' argument is null, but the fact that it's present suggests to me that one can use it. But when I set it to a string, like this, the call fails.

$response = wp_remote_get( $api_endpoint, array(
    'headers' => array(
        'Content-Type' => 'application/json',
        'X-Public' => $api_public_key,
        'X-Hash' => $contentHash,
    ),
    'body' => $body,
));

I get the error:

TypeError: http_build_query(): Argument #1 ($data) must be of type array, string given in /var/www/html/wp-includes/Requests/src/Transport/Curl.php on line 578

enter image description here

(don't worry that I included keys, etc in the above image - they are only temporary test keys)

My question is, am I able to send a body using wp_remote_get(), and, if so, what am I doing wrong?

1
  • Putting a body in as a query parameter is probably just polluting your access logs. Just use wp_remote_post(). POST method requests aren't just for write operations.
    – Walf
    Commented Sep 14, 2023 at 10:07

1 Answer 1

2

I think I've figured out the solution.

The short answer is GET requests don't usually have a body, but wp_remote_get() will take what one assigns to the body argument and make it into URL parameters. That's why it expects an array (because each element of the array becomes a parameter added to the URL).

One solution is to simply wrap the "body" in an "array()", like this:

"body" => array($body),

and then retrieve the body on the receiving end as the first request parameter.

1
  • 2
    Note that GET requests can technically have a body, but that kind of goes against the purpose of GET requests that they should be cacheable and you should get a consistent response per URL. So many tools convert the body to URL parameters, like JQuery's ajax too. But it's possible in Postman and should work
    – Kaddath
    Commented Jun 26, 2023 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.