Upgrade to Pro — share decks privately, control downloads, hide ads and more …

REST APIs for Absolute Beginners

REST APIs for Absolute Beginners

How to make a basic endpoint, use it on the frontend, and convert existing code

Tom J Nowell

July 23, 2017
Tweet

More Decks by Tom J Nowell

Other Decks in Technology

Transcript

  1. REST APIs for Absolute Beginners How to make a basic

    endpoint, use it on the frontend, and convert existing code
  2. Admin AJAX? add_action("wp_ajax_fruit", "fruit"); add_action("wp_ajax_nopriv_fruit", "fruit"); function fruit() { echo

    "bananas"; exit; } jQuery.ajax({ type : "get", url : "https://example.com/wp-admin/admin-ajax.php", data : { action: "fruit" }, success: function(response) { // } });
  3. The rest API is a is a set of pages

    that return JSON instead of HTML that have no state
  4. Adding an Endpoint add_action( 'rest_api_init', function () { register_rest_route( 'tomjn/v1',

    '/test/', array( 'methods' => 'GET', 'callback' => 'tomjn_rest_test' ) ); } ); function tomjn_rest_test() { return "moomins"; }
  5. How Do I Accept Parameters? function tomjn_rest_test( \WP_REST_Request $request )

    { return "moomins ".$request["val"]; } /wp-json/tomjn/v1/test?val=1 "moomins 1"
  6. Converting AJAX calls • Register an endpoint • Use the

    function WP Admin AJAX uses • Return what you want instead of printing it • Use the request parameter instead of $_GET $_POST etc • Update the URLs in your javascript
  7. Creating Content $.ajax( { url: wpApiSettings.root + 'wp/v2/posts', method: 'POST',

    beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data:{ 'title' : 'Hello Moon', 'content': 'Test post' } } ).done( function ( response ) { console.log( response ); } );
  8. Updating Content $.ajax( { url: wpApiSettings.root + 'wp/v2/posts/1', method: 'POST',

    beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data:{ 'title' : 'Updated Moon', 'content': 'even better post' } } ).done( function ( response ) { console.log( response ); } );
  9. Deleting Content $.ajax( { url: wpApiSettings.root + 'wp/v2/posts/1', method: 'DELETE',

    beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); } } ).done( function ( response ) { console.log( response ); } );
  10. Built in Endpoints Posts /wp/v2/posts Post Revisions /wp/v2/revisions Categories /wp/v2/categories

    Tags /wp/v2/tags Pages /wp/v2/pages Comments /wp/v2/comments Taxonomies /wp/v2/taxonomies Media /wp/v2/media Users /wp/v2/users Post Types /wp/v2/types Post Statuses /wp/v2/statuses Settings /wp/v2/settings