Chaining API calls allows you to add multiple shortcodes onto the same page and gather the data from the first call and then pass this data onto a subsequent API call.
For example you could send a users email address to API call #1 and this would return the users ‘customer_id’. You could then use this customer_id within API call #2 to update the details of this customer, or to display the details of the customer.
You can even chain API calls to different API’s.
How to chain API calls
To set this up, we will add our shortcodes to a page and use the ‘chain’ attribute in the shortcodes as shown below.
[wpgetapi_endpoint api_id='quotable' endpoint_id='random' keys='_id' format='no_display' chain='start']
[wpgetapi_endpoint api_id='quotable' endpoint_id='quotes' format='html' chain='end']
Let’s look in detail at what we are doing here. Remembering that this is just a basic example and you will need to modify the api_id and endpoint_id to work with your own endpoints.
- Shortcode 1 is calling the Quotable API to get a random quote
- The keys=’_id’ attribute will return only the id from the API call
- The format=’no_display’ attribute tells this shortcode not to output anything to the page (we just want to use the id in the next call, not display it)
- The chain=’start’ attribute tells us that this is the start of the chaining.
The endpoint screen for shortcode 1 looks like this:
The results of this endpoint shows the data that is returned. We have highlighted the _id key that we are grabbing using the keys=’_id’ attribute.
So shortcode 1 will call the random quote endpoint and return the _id key and we won’t output anything from this endpoint.
- Shortcode 2 is calling the Quotable API to get a quote
- The format=’html’ attribute tells this shortcode to output the quote as HTML
- The chain=’end’ attribute tells us that this is the last item in the chain
The shortcode 2 endpoint screen looks like this:
We use a token (chain:start) which tells this endpoint that we need to grab the data from the shortcode that is called chained=’start’, which is obviously from our shortcode 1.
That’s it. Now the _id value from shortcode 1 will be appended to this endpoint so it will become something like /quotes/gphANJ7YEjnz and shortcode 2 will output the results as HTML.