Last active
May 8, 2024 19:46
-
-
Save pashri/c889ebb79c18ca77312490217b534da4 to your computer and use it in GitHub Desktop.
API call using IAM authentication in R
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
library(aws.signature) | |
library(httr) | |
library(jsonlite) | |
library(purrr) | |
Sys.setenv( | |
AWS_ACCESS_KEY_ID = "", | |
AWS_SECRET_ACCESS_KEY = "", | |
AWS_REGION = "us-east-1" | |
) | |
aws.executeapi <- function(url, verb, query = NULL, body = NULL, headers = NULL) { | |
parsed_url <- parse_url(url) | |
datetime <- format(Sys.time(), "%Y%m%dT%H%M%SZ", tz = "UTC") | |
request_body <- toJSON(body, auto_unbox = TRUE) | |
canonical_headers <- list( | |
Host = parsed_url$hostname | |
) | |
auth <- aws.signature::signature_v4_auth( | |
datetime = datetime, | |
service = "execute-api", | |
action = paste0('/', parsed_url$path), | |
verb = verb, | |
canonical_headers = canonical_headers, | |
query_args = query, | |
request_body = if (verb %in% c('GET', 'HEAD', 'OPTIONS')) '' else request_body, | |
algorithm = "AWS4-HMAC-SHA256", | |
) | |
auth_headers <- list( | |
Authorization = paste0( | |
"AWS4-HMAC-SHA256 Credential=", auth$Credential, | |
", SignedHeaders=", auth$SignedHeaders, | |
", Signature=", auth$Signature | |
), | |
Date = datetime | |
) | |
httr::VERB( | |
verb = verb, | |
url = url, | |
body = request_body, | |
query = query, | |
do.call(add_headers, c(auth_headers, headers)) | |
) | |
} | |
aws.executeapi.delete <- partial(aws.executeapi, verb = 'DELETE') | |
aws.executeapi.get <- partial(aws.executeapi, verb = 'GET') | |
aws.executeapi.head <- partial(aws.executeapi, verb = 'HEAD') | |
aws.executeapi.options <- partial(aws.executeapi, verb = 'OPTIONS') | |
aws.executeapi.patch <- partial(aws.executeapi, verb = 'PATCH') | |
aws.executeapi.post <- partial(aws.executeapi, verb = 'POST') | |
aws.executeapi.put <- partial(aws.executeapi, verb = 'PUT') | |
# Then call the API Gateway API like: | |
response = aws.executeapi.get( | |
url = 'https://www.domain.tld/endpoint', | |
query = list( | |
param1 = 'foo', | |
param2 = 'bar', | |
param3 = 'baz' | |
) | |
) | |
data <- content(response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I needed to call an API Gateway API in R, using IAM authentication. I couldn't find anything on the internet that showed how to do this, so I figured I'd put what worked for me into a public gist.