I am building a plugin for WordPress which will communicate with some remote REST API endpoints and display data in a list format in the public-facing view of WordPress.
Which method I should go for to call the API –
-
Making request form server using
wp_remote_get()
?Pros –
A. I can give
filter
andaction
hook
to change the basicHTML
layout.B. I can use
transient
to cache data.Cons –
A. It will be slower.
-
By making a direct call to the API server from the browser using
AJAX
?Pros –
A. It will be much faster.
B. I can give a function to override to change the basic
HTML
layout.Cons –
A. Can’t provide
WordPress hooks
.
2 Answers
In general it is always better to get the information straight from the source…. but you have to think about security. Using the REST API client from a different domain will require disable CORS protections for that domain. The amount of risk related to that depends upon how tied are the domains (do they have same admins, same kind of private data and such). This should not be done lightly and requires thinking as it opens a new attack vector against the “main” site.
OTOH if the data can not be cached, it is just “stupid” to do two requests instead of one.
The right implementation is probably to “overload” the API end points on the “main” server with a different domain that do not share cookies, which will eliminate the need for CORS protection. (this obviously assumes that user authentication is not required for what you are trying to do with the API)