PokePress

REST API - How to build a webapp

Created by Michael Martin / @problogdesign

Hi, I'm Michael

Front-end lead at Deloitte Digital Belfast.

Former WordPress freelancer at Pro Blog Design.

Pro Blog Design avatar

What are we covering?

  • Why the REST API?
  • Getting started
  • New post types & taxonomies
  • Adding attributes
  • Custom endpoints

Let's start with the app...

Pokemon GO
App demo

Two Parts

  1. React web app - All UI and interactivity.
  2. WordPress API - All data, including filters & global capture counts.

Setup the API

  1. Turn on permalinks.
  2. Install the REST API plugin.
  3. Load http://yoursite.com/wp-json/wp/v2/posts

The Admin Screens

Admin UI

Custom Post Type


function pokepress_post_types() {
  register_post_type('pokemon', // Adds the 'pokemon' type
    array(
      'label' => 'Pokemon',
      'public' => true,
      'show_ui' => true,
      'capability_type' => 'post',
      'hierarchical' => false,
      'rewrite' => array('slug' => 'pokemon'),
      'query_var' => true,
      'supports' => array('title', 'editor', 'revisions', 'thumbnail'),
      'taxonomies' => array('pokemon_type'),
    )
  );
}
add_action('init', 'pokepress_post_types');
					

Custom Taxonomy


function pokepress_post_types() {
  register_taxonomy('pokemon-type', 'pokemon', // Adds 'type' tags
    array(
      'hierarchical' => false,
      'labels' => array(/* ... */),
      'show_ui' => true,
      'show_admin_column' => true,
      'update_count_callback' => '_update_post_term_count',
      'query_var' => true,
      'rewrite' => array('slug' => 'pokemon-type')
    )
  );

  register_post_type(/* ... */);
}
add_action('init', 'pokepress_post_types');
					

Display a Pokemon

App screenshot

/wp-json/wp/v2/pokemon

API Response

😞

Need to enable our custom types in the API.


register_post_type('pokemon', array(
  /* ... */
  'show_in_rest' => true
));

register_taxonomy('pokemon-type', 'pokemon', array(
  /* ... */
  'show_in_rest' => true
));
					

/wp-json/wp/v2/pokemon

API Response

πŸ˜„

But where's my Pokemon picture?

API Response

πŸ˜•

HAL (Hypertext Application Language)

HAL uses the _links property to indicate links from the current resource to other resources
- API Docs
API Response

/wp-json/wp/v2/media/16

API Response

πŸ•΅

Install Better REST API Featured Images

API Response

Much easier πŸ˜…

Custom Attributes

App screenshot
Meta Boxes

Install the Meta Box plugin


function pokepress_meta_boxes($meta_boxes) {
  $meta_boxes[] = array(
    'title' => __( 'Pokemon Attributes', 'textdomain' ),
    'post_types' => 'pokemon',
    'fields' => array(
      array(
        'id' => 'hp',
        'name' => __( 'Hitpoints (HP)', 'textdomain' ),
        'type' => 'text'
      ),
      /* Add as many fields as you need. */
    )
  );
  return $meta_boxes;
}
add_filter('rwmb_meta_boxes', 'pokepress_meta_boxes');
        

register_rest_field()


// Register all fields
function poke_register_rest_fields() {
  $fields = ['hp', 'attack', 'capture_count']; // Add more here.
  foreach ($fields as $field) :
    register_rest_field('pokemon', $field, array(
      'get_callback' => 'poke_get_custom_field_string',
      'update_callback' => null,
      'schema' => null,
    ));
  endforeach;
}
add_action('rest_api_init', 'poke_register_rest_fields');

// Fetch a simple string
function poke_get_custom_field_string($object, $field_name, $request) {
  return get_post_meta($object['id'], $field_name, true);
}
          
API Response

😎

Filter by Type

App screenshot

1. Get all Type tags: /wp-json/wp/v2/pokemon-type

API Response

Save the HAL _links post link

2. Call this URL to get all Pokemon with the tag

/wp-json/wp/v2/pokemon?pokemon-type=2

☺️

Catch'em!

(with custom endpoints)

App screenshot

register_rest_route()


add_action('rest_api_init', function() {
  register_rest_route('pokepress/v1', '/catch/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'pokepress_catch_pokemon',
  ));
});
          

Now do something...


// Increment total capture count of this Pokemon
function pokepress_catch_pokemon($data) {
  $pokemon_id = intval($data['id']);
  $capture_count = get_post_meta($pokemon_id, 'capture_count', true);

  $capture_count = empty($capture_count) ? 1 : $capture_count + 1;

  update_post_meta($pokemon_id, 'capture_count', $capture_count);
  return true;
}
          

Full power of WordPress for whatever you need.

  • Set up user accounts
  • Take content submissions / votes
  • Send emails
  • Sanitise inputs

etc.

Thank you!

Deloitte Digital