What method to use to call a REST API?

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 –

  1. Making request form server using wp_remote_get()?

    Pros –

    A. I can give filter and action hook to change the basic HTML layout.

    B. I can use transient to cache data.

    Cons –

    A. It will be slower.

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

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)

Leave a Comment