Skip to content
Snippets Groups Projects
Commit 9a911b6f authored by Calisto, Luis's avatar Calisto, Luis
Browse files

Merge branch 'rgraphql' into 'main'

Rgraphql

See merge request isric/databases/wosis-api-masterclass!2
parents 73a097a4 585808e3
No related branches found
No related tags found
1 merge request!2Rgraphql
library(httr)
library(jsonlite)
library(dplyr)
# GraphQL query
query <- '
query MyQuery {
wosisLatestProfiles(first: 2) {
continent
region
countryName
datasetCode
latitude
longitude
geomAccuracy
profileCode
}
}
'
# GraphQL endpoint
url <- 'https://graphql.isric.org/wosis/graphql'
# Send POST request
response <- POST(url, body = list(query = query), encode = "json")
# Print status_code
print(status_code(response))
# Parse JSON
parsed <- fromJSON(content(response, "text"), flatten = TRUE)
# Print JSON
json <- toJSON(parsed, pretty = TRUE, auto_unbox = TRUE)
cat(json, "\n")
## convert the from json to dataframe object
results_df <- parsed$data$wosisLatestProfiles %>% as_tibble()
results_df
\ No newline at end of file
library(httr)
library(jsonlite)
library(dplyr)
# GraphQL query
query <- '
query myQuery($first: Int, $offset: Int) {
wosisLatestProfiles(first: $first, offset: $offset) {
continent
region
countryName
datasetCode
latitude
longitude
geomAccuracy
profileCode
}
}
'
# GraphQL endpoint
url <- 'https://graphql.isric.org/wosis/graphql'
# Alternatively, for local testing
# url <- 'http://localhost:8888/wosis/graphql'
new_results <- TRUE
first <- 100
offset <- 0
all_results <- list()
while (new_results) {
# Send POST request
response <- POST(url, body = list(query = query, variables = list(first = first, offset = offset)), encode = "json")
# Parse JSON
parsed <- fromJSON(content(response, "text"), flatten = TRUE)
print(toJSON(parsed, pretty = TRUE, auto_unbox = TRUE))
result_count <- length(parsed$data$wosisLatestProfiles)
if (!("wosisLatestProfiles" %in% names(parsed$data)) || result_count == 0) {
new_results <- FALSE
cat('-------------\n')
cat('No more results\n')
} else {
cat('We have more results\n')
# update offset
offset <- offset + first
all_results <- append(all_results, list(parsed$data$wosisLatestProfiles))
}
}
# Print JSON
#cat(toJSON(all_results, pretty = TRUE, auto_unbox = TRUE), '\n')
## convert the from json to dataframe object
results_df <- bind_rows(all_results) %>% as_tibble()
results_df
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment