Real Time REST API with WordPress

Real Time REST API with WordPress

The release of WordPress 4.7 gave REST API endpoints to 27% of internet. Now the data (posts, comments, taxonomies, terms, users, options, etc.) from within your CMS is available for interaction. In order to get data from your site you have to send a request. The burden is on your API client to pester your API server with requests to ensure they have up to date data.
We live in a crazy mixed-up world with bots, microservices, and IoT. Polling the same API endpoint to see if something changed is taxing and inefficient. There is a better way with Webhooks.
Learn how subscription endpoints are the key to a real-time REST API. Notify a client that a new post published. Post a message to a Slack channel when a new comment is awaiting moderation. Receive a text message when a user resets their password. The use-cases are endless.

634b37a53babc18a5bda19722d5b41a3?s=128

Rachel Baker

March 09, 2017
Tweet

Transcript

  1. REAL TIME REST APIS by: Rachel Baker

  2. REST API ENDPOINTS Baked into WordPress 4.7+

  3. GET https://demo.wp-api.org/wp-json/wp/v2/posts REVOLUTIONARY

  4. REST APIs REQUIRE CLIENTS TO MAKE REQUESTS How can your

    client know if the response data changed?
  5. SOMETIMES YOU NEED A LITTLE PUSH • Updating headless front-end

    application views for content changes (breaking news, new comment added, etc.) • Notifying a client or micro service application of a content event (comment awaiting moderation, post updated, new order received, etc.) • Attempting to keep anything in “sync” between WordPress and another application (users, newsletter subscribers, etc.) • Breaking cache or reseting cache headers
  6. WEBHOOKS + WORDPRESS ACTIONS =

  7. WEBHOOKS A WebHook is an HTTP callback: an HTTP POST

    that occurs when something happens; a simple event-notification via HTTP POST. A web application implementing WebHooks will POST a message to a URL when certain things happen. via https://webhooks.pbworks.com/w/page/13385124/FrontPage
  8. WORDPRESS ACTIONS In WordPress; an Action is a PHP function

    that is executed at specific points throughout the WordPress Core. Developers can create a custom Action using the Action API to add or remove code from an existing Action by specifying any existing Hook. This process is called "hooking". via https://codex.wordpress.org/Glossary#Action
  9. function notify_user_registered( $user_id ) { // authentication handling not shown.

    $request = new WP_REST_Request( 'GET', '/wp/v2/users/' . $user_id ); $response = rest_do_request( $request ); $status = $response->get_status(); // $status should equal 200. $data = $response->get_data(); $callback_uri = 'https://example.com/myclient/callback/ user.registered'; wp_safe_remote_post( $callback_uri, array( 'body' => $data ) ); // check for errors. } add_action( 'user_register', 'notify_user_registered' ); Notify a callback uri when a new user is created
  10. + REST HOOKS =

  11. REST HOOKS REST Hooks itself is not a specification, it

    is a collection of patterns that treat webhooks like subscriptions. These subscriptions are manipulated via a REST API just like any other resource. via http://resthooks.org/docs/
  12. WHAT YOU NEED 1. Mechanism to store subscriptions
 2. Mechanism

    to list, create, modify, delete subscriptions via API endpoints
 3. List event hooks via API endpoint
 4. Mechanism to send hooks <—— Database table <—— Subscriptions endpoints and authentication <—— Hooks endpoints <—— Implement needed WordPress actions to send template response data to subscription uris
  13. SAMPLE HOOKS MODEL

  14. GET /wp-json/api/v1/hooks LIST HOOKS

  15. SAMPLE SUBSCRIPTION MODEL

  16. GET /wp-json/api/v1/subscriptions STORE & MODIFY SUBSCRIPTIONS POST /wp-json/api/v1/subscriptions GET /wp-json/api/v1/subscriptions/<id>

    PUT /wp-json/api/v1/subscriptions/<id> DELETE /wp-json/api/v1/subscriptions/<id>
  17. GET /wp-json/api/v1/subscriptions LIST YOUR SUBSCRIPTIONS

  18. function notify_user_registered( $user_id ) { // authentication handling not shown.

    $request = new WP_REST_Request( 'GET', '/wp/v2/users/' . $user_id ); $response = rest_do_request( $request ); $status = $response->get_status(); if ( 200 === $status ) { $data = $response->get_data(); $subscriptions = get_available_subscriptions(); foreach( $subscriptions as $subscription ) { if ( empty( $subscription['hook'] ) || 'user.created' !== $subscription['hook'] ) { continue; } wp_safe_remote_post( $subscription['uri'], array( 'body' => $data ) ); // check for errors. } return; } } add_action( 'user_register', 'notify_user_registered' ); Send response data to subscribers when a new user is created
  19. GOTCHAS • Error handling and optionally retrying connections for 4xx/5xx

    errors.
 • Performance of inline hook delivery. Consider a delayed queue system.
 • Impact of payload size. Consider reducing hook templates where possible.
 • Security and authentication.
 • You now have your own RPC API to maintain alongside your REST API.
  20. ICON CREDITS Pull by Venkatesh A.G.E Prodding by Luis Prado

    Hook by Alex Fuller Cake by Edward Boatman Valentine cake by Dinosoft Labs Newspaper by Noe Araujo Facepalm by Edward Boatman
  21. THANK YOU Rachel Baker @rachelbaker Slides are available at: https://speakerdeck.com/rachelbaker/real-time-rest-api-with-wordpress