0

I'm using wp_remote_post() to integrate with an API that requires me to send one request after another to a REST API. (The first to create a user record, the second to add a tag to it).

Using Guzzle I know you can do "Promises" similar to JavaScript, but I don't really want to bring a dependency into this if possible.

Is it sufficient for me to do something like this?

// First Request
$api_response = wp_remote_post( self::$api_base . '/subscribers' , array(
    'headers' => array(
        'Content-Type'  => 'application/json',
        'Authorization' => 'Basic ' . $account_data['api_key'] . '',
    ),
    'body' => json_encode([
        'first_name' => $data['fname'] ?? '',
        'email' => $data['email']
    ])
    )
);

// Response Code
$api_responce_code = wp_remote_retrieve_response_code( $api_response );

// Second Request (Based on First Response)
if(( ! is_wp_error($api_response)) && (200 === $api_responce_code )) {
    $api_response_2 = wp_remote_post( self::$api_base . '/subscribers' . '/' . $data['email'] . '/segments' , array(
        'headers' => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Basic ' . $account_data['api_key'] . '',
        ),
        'body' => json_encode([
            'segment_ids' => [$settings->list_id],
        ])
        )
    );
} else {
    $response['error'] = 'Something went wrong!';
}

This does work for me, but, it's not clear to me if wp_remote_post() fully completes the first request before the second one in the conditional runs or not. I'm also not sure the best way to check that. Feels too easy.

Thanks!

1
  • 1
    As far as I know, there's no asynchronicity in the wp_remote_* functions. If you've got a response back from the first wp_response_post(), then that request is finished. It might feel too easy, but it really is that easy.
    – Pat J
    Nov 7 at 3:07

1 Answer 1

1

wp_remote_post has a configuration option called blocking. Its description says:

Whether the calling code requires the result of the request.
If set to false, the request will be sent to the remote server, and processing returned to the calling code immediately, the caller will know if the request succeeded or failed, but will not receive any response from the remote server. Default true.

Since the default value is true, you can expect the call to block until a response is received. Therefore, the first request should complete before the second.

1
  • Well, that's easy enough! Guess my mind was too stuck on the promise concept. Thank ya!
    – fyrekcaz
    Nov 7 at 15:04

Your Answer

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

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