How to make a rest style plugin?

I got a little piece of code here, but it should/could probably be improved.

  • Create new query_vars
  • Create new rewrite rule
  • Redirect to specific template which then handles your parameters

Create new query vars

function register_gallery_query_vars($vars) {
   $vars[] = 'gallery_id';
   $vars[] = 'image_id';
   return $vars;
}
add_filter('query_vars', 'register_gallery_query_vars');

Add rewrite rule

function custom_rewrite_gallery() {
  add_rewrite_rule('^gallery/([0-9]+)/([0-9]+)/?', 'index.php?gallery=$matches[1]&image=$matches[2]', 'top');
}
// Change this to run ONLY on plugin activation
// Also have in mind that you need to flush rewrite rules if you change them
add_action('init', 'custom_rewrite_events');

Redirect to template

function gallery_template_redirection($template)
{
    global $wp_query;
    if(isset($wp_query->query_vars['gallery'])) { return dirname(__FILE__).'/gallery.php'; }
     else return $template;
}
add_filter('template_include', 'gallery_template_redirection', 1, 1);

Your gallery.php can then use get_query_var() to read the values and work on with them.