How to build an API as a plugin

First thing is the add rewrite rule function. You have –

add_rewrite_rule('^wp-api/pugs/?([0-9]+)?/?','index.php?__wp-api=1&pugs=$matches[1]','top');

wp-api/pugs/?([0-9]+) this means, when you request <url>/wp-api/pugs/123, you will get a query variable pugs with parameter 123.

$var = get_query_var('pugs'); // = 123

Now, you don’t really need pugs in the url as per you needs. So, just remove it this way. Also, the matching regex should not be number only. so the changed code would be –

add_rewrite_rule('^wp-api/?([^/]+)?/?','index.php?__wp-api=1&pugs=$matches[1]','top');

Final usage is:

protected function handle_request(){

    global $wp;

    $pugs = $wp->query_vars['pugs'];

    // <url>/wp-api/version/
    if( 'version' == $pugs )
        $this->send_response( 'wp-version', $this->get_wp_version() );


    // <url>/wp-api/something/
    elseif( 'something' == $pugs )
        $this->send_response( 'something', 'something' );

    else
        $this->send_response( 'Something went wrong with the pug bomb factory');
}

Leave a Comment