Search code examples
rapiauthenticationrcurl

API authentication using rCURL


I am super new to R, I tried to connect to Rosette API via R and I got curl script below. How do I internet this to R? I got my personal API key.

curl "https://api.rosette.com/rest/v1/ping" -H 'X-RosetteAPI-Key: [your_api-key]'

Thanks Peddie


Solution

  • The curlconverter package was tailor-made for this.

    You can take your cURL command line and either copy it to the clipboard or pass it in directly. If you copy it to the clipboard then you call straighten() with no parameters:

    library(curlconverter)
    
    flat <- straighten()
    

    otherwise, you can pass it in as a string:

    flat <- straighten("curl 'https://api.rosette.com/rest/v1/ping' -H 'X-RosetteAPI-Key: [your_api-key]'")
    

    That makes a list of all the URL parts which you can then pass into make_req():

    req <- make_req(flat)[[1]]
    

    make_req() turns that list into a fully functional httr call. It's vectorized, which is why it returns a list of one or more functions vs just a function.

    If you just pass in just one object, then it also copies the generated function source to the clipboard, which you can paste back into your IDE. This one generates:

    httr::VERB(verb = "GET", url = "https://api.rosette.com/rest/v1/ping", 
        httr::add_headers(`X-RosetteAPI-Key` = "[your_api-key]"))
    

    NOTE that you could also see that source by just entering req (no parens) at the R console.

    I usually examine the output and make it a bit more compact:

    GET(url = "https://api.rosette.com/rest/v1/ping", 
        add_headers(`X-RosetteAPI-Key` = "[your_api-key]"))
    

    It imports/exports %>% so it's possible to — after copying a cURL command-line to the clipboard — do:

    straighten() %>% make_req() -> req
    

    A fairy common subset of cURL command line options are supported. If one is missing that you need, just file an issue with an example. Speaking of examples, there are many more usage examples at the gh repo.