17.6 One last thing: API calls

If you ShinyApp uses API calls, there are good chances you are already doing this from R. However, there may be downsides to this approach. As an example, if you are limited by API calls (Twitter API, Google Map API). Due to these restrictions your end user may be limited in using your app.

A work around is instead of using your Server’s IP to make the API call, wrap it in Javascript so you use your user’s IP instead! This allows your ShinyApp to scale.

You use the fetch() JavaScript function to make API calls. For an example: tags$button("Get Me One!", onclick = "get_rand_beer()").

Below is a general skeleton that works with an API that does not require authentication and returns a JSON object.

  • Inside JavaScript (here, we create a function that will be available on an onclick event):
// FUNCTION definition
const get_rand_beer = () => {
  // Fetching the data
  fetch("https://api.punkapi.com/v2/beers/random")
  // What do we do when we receive the data
  .then((data) =>{
  // TTurn the data to JSON
    data.json().then((res) => {
    // Send the json to R
      Shiny.setInputValue("beer", res, {priority: 'event'})
    })
  })
  // Define what happens if we fail to fetch
  .catch((error) => {
      alert("Error catching result from API")
  })
};
  • Observe the event in your server:
observeEvent( input$beer , {
  # Do things with beer
})

NOTE: The data shared between R and JavaScript is serialized to JSON, so you will have to manipulate the format once you recieve it in R.

Learn more about fetch() at Using Fetch.