USAID-OHA-SI / grabr

OHA/SI APIs package
https://usaid-oha-si.github.io/grabr/
Other
1 stars 2 forks source link

Okta handling with wave_process_query #68

Open achafetz opened 1 week ago

achafetz commented 1 week ago

With the move to Okta, we have a temporary solution to make the PDAP Wave accessible via API.

This means updating wave_process_query to ask for the PDAP session token and to then pass that into the data post request.

This is the code that worked in testing with the assistance of Derek and Baboyma.

#dependencies
library(tidyverse)
library(vroom)
library(glue)
library(httr)
library(askpass)

#api url
base_url <- "https://wave.pdap.pepfar.net"

#setup temp file for storing
temp_file <- tempfile(fileext = ".zip")

#get country uid for API
cntry_uid <- "mdXu6iCbn2G"

#log into Okta, load DATIM, and then go to https://www.datim.org/pdapsession for the token
token <- askpass('token from https://www.datim.org/pdapsession')

#response to establish a session token
auth_result <- POST(glue("{base_url}/api/Authenticate/session"),
                    encode = 'json',
                    body = list(session_buster_token = token)
)

if (auth_result$status_code != 200) {
  cat("Wave Login failed. status_code = ", auth_result$status_code, "\n")
  cat("Wave message = ",  content(auth_result, 'text'), "\n")
  stop("Failed")
}
jsonRespParsed<-content(auth_result, as="parsed")
wave_session <- jsonRespParsed$token

#filtered request (through POST API)
post_body <- list(
  daily_frozen = 'frozen',
  fiscal_year = list(2024),
  funding_agency = list("USAID"),
  indicator = list("TX_CURR"),
  uid_hierarchy_list = list(glue('-|-|{cntry_uid}'))
)

#POST request
POST(
  glue('{base_url}/api/data/ou_im'),
  set_cookies(wave_session = wave_session),
  encode = 'json',
  body = post_body,
  write_disk(temp_file, overwrite=TRUE)
)

#load data
df_wave <- vroom(temp_file)