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

Eba4cc68bfbc2b59c3c3a3cf789075f0?s=128

Tom J Nowell

July 23, 2017
Tweet

Transcript

  1. 1.

    REST APIs for Absolute Beginners How to make a basic

    endpoint, use it on the frontend, and convert existing code
  2. 3.

    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. 7.

    The rest API is a is a set of pages

    that return JSON instead of HTML that have no state
  4. 9.

    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. 11.
  6. 13.

    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"
  7. 14.

    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
  8. 16.

    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 ); } );
  9. 17.

    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 ); } );
  10. 18.

    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 ); } );
  11. 19.

    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
  12. 24.
  13. 25.