This guide will walk you through setting up dynamic variables in endpoints.
In our example we will use a real life API to retrieve a random cat image. This is the API we will use – https://thatcopy.pw/catapi/docs.html
We are wanting to call this endpoint in particular – https://thatcopy.pw/catapi/restId/1
Notice the number 1 at the end of the end of the endpoint. This number represents the ID of the cat picture that we will retrieve and we want to make it random.
Endpoint settings
Within the admin setup of your endpoint, we would replace the number 1 from our example above with the number 0 wrapped in curly braces – {0} – so our endpoint now looks like the image below.
Wrapping the number in {} firstly tells the plugin that this is a variable. Using the number 0 means it is our first variable as it is ‘zero indexed’. If there were multiple different variables required, they would just be sequentially numbered like {0} {1} {2} etc. You can use unlimited variables.
Output the data using Template Tag
Let’s say you have a logged in user to your WordPress website and their API User ID (not their WordPress user ID) is stored in the usermeta table within your website. You could retrieve your users data from our pretend API by doing something like this:
// get random number from 1 - 20
$rand_id = rand(1,20);
// call the API using the wpgetapi_endpoint() template tag
$data = wpgetapi_endpoint( 'cat', 'rest',
array(
'debug' => true,
'endpoint_variables' => array( $rand_id ),
)
);
// you now have the data stored within $data to use however you like
echo $data;
We have used the ‘endpoint_variables’ attribute and added the $rand_id as the first, zero indexed item in the array. We could add unlimited variables into here as long as they are matched with the {0} {1} {2} etc variables in the endpoint settings.
Output the data using Shortcode
You can also use set endpoint variables within the shortcode, though this will be less useful as you can’t really have a dynamic variable within a shortcode as such. But in this example below we are getting the ID 14.
[wpgetapi_endpoint api_id='cat' endpoint_id='rest' debug='true' endpoint_variables='14']