Last active
February 7, 2024 12:33
-
-
Save rentrop/83cb1d8fc8593726a808032e55314019 to your computer and use it in GitHub Desktop.
Querying GraphQL with R using httr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assuming the following GraphQL: https://github.com/calebmer/postgraphql/tree/master/examples/forum | |
# Deploy to AWS via https://github.com/rentrop/serverless-postgraphql | |
require(httr) | |
require(jsonlite) | |
# Define helper function -------------------------------------------------- | |
url <- "https://your-endpoint/graphql" | |
GQL <- function(query, | |
..., | |
.token = NULL, | |
.variables = NULL, | |
.operationName = NULL, | |
.url = url){ | |
pbody <- list(query = query, variables = .variables, operationName = .operationName) | |
if(is.null(.token)){ | |
res <- POST(.url, body = pbody, encode="json", ...) | |
} else { | |
auth_header <- paste("bearer", .token) | |
res <- POST(.url, body = pbody, encode="json", add_headers(Authorization=auth_header), ...) | |
} | |
res <- content(res, as = "parsed", encoding = "UTF-8") | |
if(!is.null(res$errors)){ | |
warning(toJSON(res$errors)) | |
} | |
res$data | |
} | |
# Define queries ---------------------------------------------------------- | |
auth_query <- 'mutation { | |
authenticate(input: {email: "[email protected]", password: "iFbWWlc"}) { | |
jwtToken | |
} | |
}' | |
current_person_query <- '{ | |
currentPerson { | |
fullName, | |
latestPost{ | |
headline | |
} | |
} | |
}' | |
# Run queries ------------------------------------------------------------- | |
token <- GQL(auth_query)$authenticate$jwtToken | |
GQL(current_person_query, .token = token) | |
# $currentPerson | |
# $currentPerson$fullName | |
# [1] "Sara Powell" | |
# | |
# $currentPerson$latestPost | |
# $currentPerson$latestPost$headline | |
# [1] "Ameliorated optimal emulation" | |
# (optional) Simplify result ---------------------------------------------- | |
require(purrr) | |
flatten(GQL(current_person_query, .token = token)) | |
# $fullName | |
# [1] "Sara Powell" | |
# | |
# $latestPost | |
# $latestPost$headline | |
# [1] "Ameliorated optimal emulation" | |
# A more complex example -------------------------------------------------- | |
all_people_query <- '{ | |
allPeople(first: 3) { | |
edges { | |
node { | |
id | |
fullName | |
latestPost { | |
id | |
headline | |
} | |
} | |
} | |
} | |
}' | |
GQL(all_people_query, .token = token)$allPeople$edges %>% | |
map_df(~transpose(.) %>% simplify_all) | |
# # A tibble: 3 × 3 | |
# id fullName latestPost | |
# <int> <chr> <list> | |
# 1 1 Sara Powell <list [2]> | |
# 2 2 Andrea Fox <list [2]> | |
# 3 3 Stephen Banks <list [2]> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment