17

First of all, I understand that this is a plugin at current point but it is most certainly almost part of WordPress anyway. So I hope that this is not getting flagged as off-topic.

I've read their official docs, a lot of other articles and watched tutorial videos but Im still not getting some of the points.. This is certainly the future of WordPress, it is very handy for mobile app developement and using/sharing data between different sites but: what does it do for my site only?


Consider this:

Im currently working on the comments. I want comment section to load only when user scrolls to comment section (with -200px offset, so that there's no delay).

  • Im going to trigger ajax call when user scrolls to that point
  • Ajax call sends some data with it, like post_id etc
  • Run WP_Comment_Query() in server
  • Send JSON data back to client with comment relations, names, content etc
  • Use JavaScript document.createElement(), innerHTML etc to create and output comments

Now.. Why would I use REST API instead? What's the use for me? Just futureproof?

I would still need to use JavaScript to output all the data I get.. I didn't find any good articles why or for what I should use REST API (except data transfer between sites and mobile app developement)..

  • Using the REST API in favor to the way you described would give you the benefit of a structured and unified way. You doesn't need to deal with the content collectors (comment query) or the response format (json). There might also some improvements with caching. The downside I see in general is, that templating moves completely to the browser which – in my »backend-developer« opinion – raising performance issues. – David Mar 2 '16 at 18:52
  • How do you plan on sending the JSON data back to the client? How are you building the server side code? – czerspalace Mar 2 '16 at 18:54
  • michaelbromley.co.uk/blog/418/… – jgraup Mar 2 '16 at 20:16
  • @David Basically REST API does all the queries itself and I just need to feed it query strings as parameters? About templating.. I see what you're saying, fortunately hardware gets more powerful with every year. Unfortunately there will always be people who refuse to envolve in that matter (old IE users, Im looking at you). – N00b Mar 2 '16 at 21:26
  • @czerspalace 1. WP_Comment_Query() 2. Construct array of comments each with array of parameters in while loop 3. json_encode() 4. echo encoded data back. All this in wp_ajax and/or wp_ajax_nopriv function. – N00b Mar 2 '16 at 21:29
8

At its current state, it is a badly engineered feature that do not have any real advantage for a competent developer.

The basic idea, as it stands at the time this answer is written, is to expose WordPress core functionality as JSON REST API. This will enable decoupling of the WordPress "business" logic from the UI and enable creating different full or partial UIs to manage and extract information from wordpress. This by itself is not a revolution, but an evolution. just a replacement of the XML-RPC API which by itself kinda streamlines the HTTP based for submission API.

As with any evolution, at each step you might ask yourself, what advantage do you get from the former state, and the answer is probably "not much", but hopefully the steps do accumulate to a big difference.

So why the negative preface to this answer? Because my experience as software developer is that it is rarely possible to design a generic API that is actually useful without having concrete use cases to answer to. A concrete use case here can be replacing the XML-RPC API for automated wordpress management, but any front end related has to be site specific and since there is a huge performance penalty for every request sent from the client to the server you can not just aggregate use of different API to get the result you want in a way in which the users will remain happy. This means that for front end, for non trivial usage, there will still be very little difference in development effort between using the AJAX route and the REST-API route.

  • Thank you, this makes things only worse! I sincerely just can't make up my mind which road to take.. What I do know is I will probably need to make a mobile app in the future. Your advice is that REST API at current state is crap? – N00b Mar 3 '16 at 19:16
  • No, just that it doesn't show out of the box any real advantage. As for if to use it or not, as always you should use the tool you know better, especially you should take into consideration that the rest api is still in beta. I would still consider registering routes with the part of the api that is already in core as it will give you a cleaner urls, ones that you will be able to cache if needed, something you can't do with the ajax end point. – Mark Kaplun Mar 3 '16 at 19:34
3

The two overarching advantages are:

  1. You can (eventually) do all admin tasks without the admin interface.
  2. You can get all data for display and eliminate the front end (and writing PHP) completely.

Regarding your example specifically-

Replace steps 3 & 4 with the REST API, and replace steps 1, 2, and 5 with Backbone.js. BOOM, dynamic web application. Or maybe you're more comfortable doing the complex routing necessary for your site with Python instead.

  • Im very irritated about the fact that everybody online says that dynamic web application meaning is very subjective (and that's why they don't tell exactly what it is) which means that I don't 100% know what it is compared to not dynamic website.. What's your version of it? This is like one thing I need to know if to use REST API or not.. – N00b Mar 3 '16 at 19:21
  • 2
    Application meaning something beyond rendering static blog pages that link to other static blog pages, a more seamless "app like" experience. Scroll down to the examples on the backbone site. – Milo Mar 3 '16 at 19:53
3

Well, a few things actually.

  1. It lets you run specific functions as needed, rather than requiring all of the computation of an entire page load. So, you could update the comments periodically with fairly low overhead without needing a page refresh by just calling that API endpoint and updating the data on your page. This concept will eventually be extrapolated into SPAs (single page applications) which load the "client" site quickly once, and emulates all page "changes" without needing to re-pull the page's HTML each time. This is already very popular with the advent of frameworks such as Angular, Ember, and React. Sites may respond with blazing speed, while both offloading some computational power to the end-user (render cycle, non-business logic) and reducing the overall number of calls to the server significantly (only pull the data that you need, rather than reloading everything each time).

  2. It separates the business logic and the renderer. Yes, you can use the API with another PHP site spitting out the results, or handle it with Javascript like you mentioned, but you can also consume it with a native mobile application, desktop application, etc. Not only that, but you could have one of each all talking to the same API, which consistently performs the same business logic, which in turn creates consistency and reliability across the various clients consuming the API.

APIs are good because they separate the concerns of logic and display.

  • About the first point.. Why is it better than regular JavaScript ajax checking updates in intervals and updating dynamically? – N00b Mar 2 '16 at 21:49
  • 2
    Well, "regular" ajax calls ARE just calls to an API! There isn't really a difference. The goal of the REST API is to provide such an API for the core Wordpress functionality. This way you can do more operations using AJAX, native apps, desktop apps, etc. The "REST" part of it is just a system of rules/standards that define how the API should be constructed so that it is easy to develop with and maintain. – Colt McCormack Mar 3 '16 at 3:04
2

The WordPress REST API is the new hotness. With single page js driven applications, and WordPresses desire to become an app platform this makes a lot of sense. The plan is to replace XML-RPC with the REST API (which is a good thing for security reasons alone!)

https://make.wordpress.org/core/2015/09/21/wp-rest-api-merge-proposal/

  • The New York times new site is built on it, apparently.
  • It allows mobile apps and other external services to access wp content (like wp-cli)
  • It allows developers to build a single-page app front end with their favorite JSON consuming framework of the week, and have all of the cool interactions at their fingertips.
  • It allows for separation of concerns (as mentioned above) and greater independence between the back-end and front-end teams.

It's another set of tools to take WordPress forward. And, although it's been a meandering journey to get to where we are, I think it's worth taking the time to explore and understand it.

1

First things first - REST is lightweight

In one line - When we use REST APIs we do all data rendering at client side (loops , conditions and server side calls etc. ) saving bandwidth and at the same time our application becomes ready for any mobile platform , 3rd party integrations and modularized (sepration of concern between frontend and server side ).

Dont you want this ?

0

In addition to the 2 great points @Milo mentioned, I specifically use the REST API to expose my data to non-WordPress applications. We have a Chrome extension that pulls information from our WordPress database, and this is accomplished by hitting REST API endpoints with POST requests.

0

CONSISTENT Infrastructure

The REST API is consistent and human-readable. It's self-documenting.

GET wp-json/wp/v2/posts is pretty clear what it does. It GETs some posts.

You have a namespace: wp, a version: v2 and an object collection posts

Can you guess what: GET wp-json/wp/v2/posts/5 does? How about : GET wp-json/wp/v2/posts/5/comments How about: GET wp-json/shop/v2/orders/345/lines/11/price

A developer can easily guess by looking at that, it's going to get the price of line 11 on order 345 even without reading the documentation. The dev can even easily tell that it's coming from the shop Plugin as it is namespaced.

How about POST /wp-json/v2/posts title=New Blog Post How about PUT /wp-json/v2/posts title=New Title

That's pretty clear as well. It makes a new post. By the way, it returns the ID of the new post. It's not about AJAX OR the REST API. AJAX is simply a technology that accesses the REST API. Whereas, before, you would have to come up with a bunch of abstract ajax function names like: get_price_for_lineitem( $order, $line ). Is that going to return just a number, or a JSON object? I'm not sure, where's the documentation. Oh... was the ajax call get_order_line_price or get_lineitem_price.

The developer doesn't have to make these decisions, because the existing wp-json api provides a good base model to follow when creating your own endpoints. Sure, a plugin or api developer can break these rules, but in general it's easier to follow a standard that's already been set and most developers would much rather follow a pattern already set ( see how pervasive jQuery patterns are now ).

ABSTRACTION without distraction

Do I care about how POST /wp-json/mysite/v1/widgets title=Foobar works? Nope. I just want to create a new Widget and I want the ID in return. I wanna do it from a form on my front end without refreshing the page. If I make a request to a URL, I don't care if it's PHP,C#, ASP.NET or any other technology. I just want to create a new Widget.

The REST API decouples the backend from the front. Technically, if your API is good enough, you could change your entire backend stack. As long as you maintained the same REST API structure, anything that depended on the API would not be affected.

If your REST API is simple and consistent enough, using a noun like Widgets as a collection of objects and noun/identifier like Widget/2 to indicate a single entity, it's really straightforward to write that API in a vastly different technology as it's more or less basic database plumbing code.

Uses Standard HTTP Request verbs.

REST APIs leverage the core of how the web works and the VERBs ( read: action ) that you use map to standard data CRUD functions.

CREATE : POST
READ   : GET
UPDATE : PUT/PATCH
DELETE : DELETE

There are more HTTP verbs, but those are the basics. Every single request over the internet uses these verbs. A REST API sits right on top of the model the web is built upon requests. No need for any communication layer or abstraction model in between. It's just a standard http request to a URL and it returns a response. You can not get much simpler than that.

Essentially, it makes a developer more aware of the nuts and bolts of how the web actually works and when you get closer to understanding how the underlying protocols work, you end up making a more efficient better product.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.