How to call API in WordPress

If you need to call an external API from your WordPress theme or plugin you can use basic couple of functions.

wp_remote_get function

This function performs an HTTP get requests and returns its response, this function receives two parameters $url and $args.

string $url is the API you need to perform a request on it.

array $args is an array of the request arguments i.e. timeout, which is the time in second after it the request will be terminated.

Example of wp_remote_get

/** @var array|WP_Error $response */
$response = wp_remote_get( 'http://www.example.com/index.html' );
 
if ( is_array( $response ) && ! is_wp_error( $response ) ) {
    $headers = $response['headers']; // array of http header lines
    $body    = $response['body']; // use the content
}

wp_remote_post function

This function performs HTTP post request and returns with its response, this function receives two parameters $url, $args.

Just as wp_remote_post, the $url is string of your API and $args is an array of arguments that can be passed to the request.

Example of wp_remote_post

$response = wp_remote_post( $url, array(
    'method'      => 'POST',
    'timeout'     => 45,
    'redirection' => 5,
    'httpversion' => '1.0',
    'blocking'    => true,
    'headers'     => array(),
    'body'        => array(
        'username' => 'bob',
        'password' => '1234xyz'
    ),
    'cookies'     => array()
    )
);
 
if ( is_wp_error( $response ) ) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    echo 'Response:<pre>';
    print_r( $response );
    echo '</pre>';
}

If you need to add basic authentication to your request, you can use Authorization key in headers array as follow.

$response = wp_remote_post( $url, array(
    'body'    => $data,
    'headers' => array(
        'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
    ),
) );

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top