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!
wp_remote_*
functions. If you've got a response back from the firstwp_response_post()
, then that request is finished. It might feel too easy, but it really is that easy.