Proxy External API request in PHP from Edit.js in Block Plugin

I'm working with a third-party API that has optional filters on their API. I'm creating a block where the user has two select elements in Edit.js that are displayed on the backend of the block. They can select filters, specialty, and location, these values are then stored in attributes.

Once a user changes a select, I want to fire off a PHP request using these attributes passed to the PHP function that uses wp_remote_get() to build the proxy and dump the data into the rest point.

I have the Edit.js function setup but am unsure how to call the PHP function from the Edit.js file with the passed block attributes.

Topic block-editor wp-remote-get rest-api Wordpress

Category Web


Okay, I figured it out!

First, I created a rest endpoint in PHP.

https://github.com/bbuilds/ih-top-nurses-block/blob/main/inc/rest.php#L11

The rest point has optional parameters using regex and then in the register_rest_route() callback builds a fetch URL depending on the parameters passed to the WP-REST endpoint.

It then fires to the external API wp_remote_get($fetch_url) and dumps the data into the REST endpoint.

https://github.com/bbuilds/ih-top-nurses-block/blob/main/src/edit.js#L77

Then in my block edit function, I set up the internal rest API call using apiFetch from "@wordpress/api-fetch" using a similar buildFetch API.

Full repo: https://github.com/bbuilds/ih-top-nurses-block

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.