PeterJohn Hunt

Building a WordPress API Request

In an effort to put more content on this blog, i’ve decided to try and take some simplified quick and dirty versions of code i’ve written or concepts that i’ve re-used in various scenarios. Below is an example function, with commenting, of what a starter function to make a server side request to a JSON api might look like!

function api_request($endpoint='', $param=array(), $args=array(), $lifespan=HOUR_IN_SECONDS){
    $apikey = 'your api key here'; // maybe get from the db
    $base   = 'http://my.api.base/api'; // maybe use a const in a class

    // ensure we have what we need
    if ( !$apikey ) return new WP_Error('request', 'no api key', 'APIKEY');

    // prepare url
    $url = trailingslashit($base) . $endpoint;

    // prepare url param plus defaults
    $param = wp_parse_args($param, array(
        'access_key' => $apikey // do various filters or authenticate
    ));

    // prepare request args plus defaults
    $args = wp_parse_args($args, array());

    // build the full url
    $full_url = add_query_arg($param, $url);

    // first check for a cached version
    if ( $lifespan ) {
        $key    = $endpoint .'::'. md5($full_url);
        $cached = get_transient($key);

        if ( $cached !== false ) {
            return $cached;
        }
    }

    // make the request
    $request = wp_remote_get($full_url, $args);

    // parse the json response
    $response = json_decode( wp_remote_retrieve_body($request) );

    // check for request errors i.e. unauthorized, 503 error, etc
    if ( is_wp_error( $request ) || ( !in_array($request[ 'response' ][ 'code' ], array( 200, 201, 204 )) ) ) {
        return new WP_Error("request", 'unknown', '000');
    }

    // check for api definied errors i.e. $response->success, $response->error, etc
    if ( empty($response) ) {
        return new WP_Error('type', 'message', 'code');
    }

    // save a cached version
    if ( $lifespan ) {
        set_transient( $key, $response, HOUR_IN_SECONDS );
    }

    return $response;
}

All in all, this is pretty light weight, and very quickly a custom table and caching via cron would be a better option than making a request on the fly and caching it after the fact. Hopefully the concepts here are helpful none the less!