Using pins for Shiny with ever-changing data

End-to-end workflow with Posit Team

2024-08-28

Today’s project

Workflow

Pulling data from an API

  • Pulling from an API can be done with requests in Python or {httr2} in R
data-pull.Rmd
```{python}
import requests
from requests.auth import HTTPBasicAuth
import json

username = "ivelasq@gmail.com"
api_key = r.api_key

social_url = "https://ivelasq.atlassian.net/rest/api/3/search?jql=project%20=%20KAN%20AND%20text%20~%20%22\%22social\%22%22"

social_results = get_response_from_url(social_url, username, api_key)
```
  • In R, we can then convert the results into a dataframe using {jsonlite}
data-pull.Rmd
```{r}
dat_json <-
 py$social_results |>
 jsonlite::fromJSON()
 
/* Clean final data here */
```


How can we keep the results up to date?

Enter pins



Using pins

Create a file for connecting to a board and writing a pin:

data-pull.qmd
```{r}
board <-
  pins::board_connect(
    auth = "manual",
    server = Sys.getenv("CONNECT_SERVER"),
    key = Sys.getenv("CONNECT_API_KEY")
  )
```

/* Data pull and cleaning goes here */

```{r}
pins::pin_write(board = board,
                x = pin_dat,
                name = "isabella.velasquez/pin_dat")
```

Read a pin:

file.R
pin_dat <-
  pins::pin_read(name = "isabella.velasquez/pin_dat",
                 board = board)

Updating pins

Schedule refreshes of pins on Posit Connect:

Shiny

Shiny is a framework for creating web applications using R code.

Shiny and reactivity

Shiny uses the reactive programming model.

  • Allows the app to automatically update outputs whenever the underlying data or user inputs change
  • Reactive expressions automatically re-execute when their dependencies change
  • Trigger actions in response to changes in reactive values

See how the greeting updates automatically as you type:

How can we do this with data?

Enter pin_reactive_read()

pin_reactive_read() wraps the results of pin_read() into a Shiny reactive.

  • Use pinned data within your app
  • Have the results automatically recompute when the pin is modified

Use it like so:

app.R
pin_reactive_read(board, name, interval = 5000)


Let’s see it in action!