How can I create a button that will trigger an API

Hello, I have created an EndPoint and successfully tested it. How can I make a button to trigger when I click a button on the website. How can I assign the button to trigger the API? Each time I navigate to “Advanced” make an edit to the button, I click the “source” for REST API that I named it. Save it and click the button on the site.

I have also tried to create a custom code but it is not assigning to the button to trigger the API. Can someone send me specific instructions how to trigger an API using a button?

Anyone know how to do this?

@OMGItzSteve

Would you consider doing it with JavaScript? If yes, I can write you example code

Hey @dejan !

I for one would love to see an example of how to do this. More specifically, how to make the data available to the page once it has been received.

Also, it would be helpful to see how to do this for REST API endpoints defined in the REST API plugin and also how to make requests to the internal CMS.

Yeah could you show me an example with and without JS?

I Agree! I would like to see an example as well

Hey,

you can create a JS file with onReady event. It will look like this:
image

Then add some ID on your button which we are going to use in our JavaScript.

Now you can use code below to achieve something like that.

$('body').on('click', '#button_ID', function() {
    fetch('YOUR_API_ENDPOINT', {
        method: 'GET', // Or 'POST', depending on your API
        headers: {
            // Headers, if required
        }
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
});
1 Like

This is great! Thank you, @Pakic!

Is it possible to use Variables in Files? Let’s say we have an API key that we need to use in several files. It would be ideal to store that somewhere centrally so we don’t have to go into each file to update it manually.

Thanks!