Calling API’s

loading data

Below you can try to get data from an API. This is not yet possible using webR for technical and security reasons. In theory, it would go like this:

This is the Give Food API at givefood.org.uk and shall give us a brief introduction on how to work with API’s. We need two packages: httr and jsonlite. We are pulling data from a data source that does not need a key foodbank.

library(httr)
library(jsonlite)

foodbank <- httr::GET("https://www.givefood.org.uk/api/2/foodbanks/")

foodbankcontent <- httr::content(foodbank, as = "text")

foodbankJSON <- jsonlite::fromJSON(foodbankcontent)
Response [https://www.givefood.org.uk/api/2/foodbanks/]
  Date: 2024-10-05 07:50
  Status: 200
  Content-Type: application/json
  Size: 1.28 MB
[
  {
    "name": "Lapford Food Bank",
    "alt_name": null,
    "slug": "lapford",
    "phone": "0136383788",
    "secondary_phone": null,
    "email": "foodbank@lapfordcc.org.uk",
    "address": "Victory Hall\r\nLapford\r\nDevon\r\nEX17 6PZ",
    "postcode": "EX17 6PZ",
...

But we can “fake” an API call, just to be able to play around a little with json files. For this we will download the data that is provided by the API as a csv and re-read it into R.

processing data

Ok, so now we have data, but what can we do with it? Below is some code where we count the foodbanks according to region in the UK. The count() command is an abbreviation of the group_by() command and the summarise() command. It is quicker, but not as versatile. We use it here, to get some quick results.

plotting data

We then add a ordered barplot so show the counts. Piece o’ cake!

Notice that we have ordered the x-axis to start with the highest bar. This makes barplots much more readable as if we would not have done this.