Question

I have an external api which takes json body as payload. I am trying to send multiple parallel requests. So I am not using wp_remote_post()

The wp_remote_post() version of my code works perfectly.

Sending JSON payload using wp_remote_post()

This works!

        $response = wp_remote_post($url, [
            'body' => json_encode($registrants), // requried keys [firstName, lastName, email]
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken,
                'Content-Type' => 'application/json; charset=utf-8'
            ],
            'data_format' => 'body',
            'timeout' => 10,
        ]);

        return json_decode(wp_remote_retrieve_body($response));

Now I am trying to do the same with Request::request_multiple() But data isn't sending as json body.

Sending JSON payload using Request::request_multiple()

Does not work!

    $requests[] = [
            'url' => $url,
            'type' => 'POST',
            'body' => json_encode($registrant), // requried keys [firstName, lastName, email]
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken,
                'Content-Type' => 'application/json; charset=utf-8'
            ],
            'data_format' => 'body',
            'timeout' => 30,
        ];

    $options = [
        'data_format' => 'body'
    ];

    $resp = Requests::request_multiple($requests, $options);
    foreach($resp as $response){
        var_dump($response);
        $responses[] = json_decode($response->body);
    }

The error I am getting from API is very specific and throws when it doesn't get JSON body payload.

Was it helpful?

Solution

You can't.

The requests library that comes bundled in WordPress doesn't support this. The reason for this is that the request_multiple function only accepts these parameters:

* @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request}

body is not one of those parameters, which explains why your request is failing. A reading of the code confirms this is the case down to the fsock/curl levels of the library.

Instead:

  • Perform non-parallel requests if you intend to continue using the Requests library
  • Switch to an alternative library such as Guzzle

I'd also recommend opening issues on GitHub, there doesn't appear to be any technical reason it couldn't be changed to support the body parameter other than that nobody added it when those interfaces were written

OTHER TIPS

Did you notice that the $registrant variable is spelled differently in the two cases?

If this is not a problem try printing out the value of json_encode($registrant) before you send it and see if it looks right.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top