Skip to content

Instantly share code, notes, and snippets.

@leeper
Last active November 28, 2015 14:19
Show Gist options
  • Save leeper/caffa5bee3d6bc4a83e9 to your computer and use it in GitHub Desktop.
Save leeper/caffa5bee3d6bc4a83e9 to your computer and use it in GitHub Desktop.
magpie: Make API endpoint wrappers with ease
endpoint <- function(verb, url, body = (verb %in% c("POST", "PUT")), encode = "json", query, headers, dots = TRUE, class) {
f <- function() {}
if (body) {
if (dots) {
if (missing(headers)) {
if (missing(query)) {
formals(f) <- alist(body = , ... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...), body = quote(body), encode = encode))
} else {
formals(f) <- alist(body = , ... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...), body = quote(body), encode = encode))
}
} else {
if (missing(query)) {
formals(f) <- alist(body = , ... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...), body = quote(body), encode = encode))
} else {
formals(f) <- alist(body = , ... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...), body = quote(body), encode = encode))
}
}
} else {
if (missing(headers)) {
if (missing(query)) {
formals(f) <- alist(body = )
body(f)[[2]] <- as.call(list(verb, url, body = quote(body), encode = encode))
} else {
formals(f) <- alist(body = )
body(f)[[2]] <- as.call(list(verb, url, body = quote(body), encode = encode))
}
} else {
if (missing(query)) {
formals(f) <- alist(body = )
body(f)[[2]] <- as.call(list(verb, url, body = quote(body), encode = encode))
} else {
formals(f) <- alist(body = )
body(f)[[2]] <- as.call(list(verb, url, body = quote(body), encode = encode))
}
}
}
} else {
if (dots) {
if (missing(headers)) {
if (missing(query)) {
formals(f) <- alist(... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...)))
} else {
formals(f) <- alist(... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...)))
}
} else {
if (missing(query)) {
formals(f) <- alist(... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...)))
} else {
formals(f) <- alist(... = )
body(f)[[2]] <- as.call(list(verb, url, quote(...)))
}
}
} else {
if (missing(headers)) {
if (missing(query)) {
body(f)[[2]] <- as.call(list(verb, url))
} else {
body(f)[[2]] <- as.call(list(verb, url))
}
} else {
if (missing(query)) {
body(f)[[2]] <- as.call(list(verb, url))
} else {
body(f)[[2]] <- as.call(list(verb, url))
}
}
}
}
body(f)[[3]] <- call("structure", class = quote(class))
return(f)
}
# quick tests
# endpoint("GET", "http://www.example.com", query = list("arg1", "arg2"))
# useful notes: http://stackoverflow.com/questions/12982528/how-to-create-an-r-function-programmatically
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment