Skip to content

Instantly share code, notes, and snippets.

@dickoa
Created June 21, 2024 17:15
Show Gist options
  • Save dickoa/051d80e653639e716e67364113f00db7 to your computer and use it in GitHub Desktop.
Save dickoa/051d80e653639e716e67364113f00db7 to your computer and use it in GitHub Desktop.
Pull DTM data from API using R and httr2
library(tidyverse)
library(httr2)
library(cli)
url <- 'https://dtmapi.iom.int/api/IdpAdmin2Data/GetAdmin2Data'
payload <- list(operation = "",
countryName = "Afghanistan",
admin0Pcode = "",
reportingDate = list(fromDate = "2018-12-31", toDate = "2023-05-31"),
reportMonthRange = list(monthFrom = list(year = 2000L, month = "1"),
monthTo = list(year = 2024L, month = "12")),
roundNumber = list(from = 0L, to = 0L))
response <- request(url) |>
req_body_json(data = payload) |>
req_perform()
if (resp_status(response) == 201) {
data <- response |>
resp_body_json() |>
pluck("result") |>
bind_rows()
} else {
cli::cli_alert_danger("Failed to retrieve data (http code {resp_status(response)})")
}
glimpse(data)
## > glimpse(data)
## Rows: 3,867
## Columns: 14
## $ id <int> 52905, 53045, 55107, 51940, 51338, 55248, 55251, 55261, 55277, 55403,…
## $ operation <chr> "Returns and displacement in Afghanistan", "Returns and displacement …
## $ admin0Name <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanis…
## $ admin0Pcode <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG",…
## $ admin1Name <chr> "Parwan", "Hirat", "Maidan Wardak", "Khost", "Bamyan", "Ghazni", "Zab…
## $ admin1Pcode <chr> "AF03", "AF32", "AF04", "AF14", "AF10", "AF11", "AF26", "AF16", "AF25…
## $ admin2Name <chr> "Charikar", "Gulran", "Chak-e-Wardak", "Gurbuz", "Bamyan", "Ajristan"…
## $ admin2Pcode <chr> "AF0301", "AF3208", "AF0404", "AF1403", "AF1001", "AF1118", "AF2606",…
## $ numPresentIdpInd <int> 4187, 3502, 105, 3864, 20246, 84, 8591, 56, 13074, 1730, 4749, 119, 8…
## $ reportingDate <chr> "2018-12-31T00:00:00", "2018-12-31T00:00:00", "2018-12-31T00:00:00", …
## $ yearReportingDate <int> 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 201…
## $ monthReportingDate <int> 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 1…
## $ roundNumber <int> 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, …
## $ assessmentType <chr> "BA", "BA", "BA", "BA", "BA", "BA", "BA", "BA", "BA", "BA", "BA", "BA…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment