Access OpenAI (json) API from R - r

I want to access the OpenAI API with the following curl command from R:
curl https://api.openai.com/v1/engines/davinci/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"prompt": "This is a test", "max_tokens": 5}'
I think the curl package (on CRAN) will be the best option(?). I have never used this package so can anyone help me getting started with this simple call?

It can easily be done with the httr package (on CRAN), hat tip to #r2evans:
library(httr)
myurl <- "https://api.openai.com/v1/engines/davinci/completions"
apikey <- "YOUR_API_KEY"
seed_text <- "This is a test"
tokens <- 5
output <- POST(myurl, body = list(prompt = seed_text, max_tokens = tokens), add_headers(Authorization = paste("Bearer", apikey)), encode = "json")
content(output)$choices[[1]]$text
## [1] " of a national emergency communication"

Related

Adding --data to R curl_fetch_memory()

I want to create an R script to use instead of a curl request.
Using curl, I use a Google API which requires the --data option. I am not sure how to add this option to my curl request using the curl package.
The request that works using Git Bash is as follows:
API_KEY="[xyz]"
curl "https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=$API_KEY" \
--header 'Content-Type: application/json' \
–-data '{"url": "https://www.example.com/"}'
This is my R code, which doesn't send the necessary URL to return anything good:
library(curl)
API_KEY = "xyz"
h <- new_handle()
handle_setheaders(h,
"Content-Type" = "application/json"
)
r <- curl_fetch_memory(url = paste0("https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=",API_KEY), h)
So how can I add the --data option using the curl package?
You can use the lower-level curl if you really want to. In this case your original CURL command is performing a POST action with a JSON encoded body. The equivalent of that in the R curl library would be
library(curl)
API_KEY <- "xyz"
url <- paste0("https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=", API_KEY)
payload <- charToRaw('{"url": "https://www.example.com/"}')
h <- new_handle()
handle_setopt(h, post=TRUE, postfields=payload)
handle_setheaders(h, "Content-Type" = "application/json")
r <- curl_fetch_memory(url = url, h)
cat(rawToChar(r$content))

Reading API - code from Curl to R

I am trying to read a json from an authenticated API using R, but not sucessfully.
I have the Curl code and tried to convert it to R using "curlconverter" library and also tried to get it using "httr" library.
curl -X GET \
'https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1' \
-H 'Cache-Control: no-cache' \
-H 'x-glb-token: mytoken'
I would appreciate a solution to write this code in R.
library(curlconverter) # devtools::install_github("hrbrmstr/curlconverter")
u <- "curl -X GET 'https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1' -H 'Cache-Control: no-cache' -H 'x-glb-token: mytoken'"
straighten(u) %>%
make_req()
That makes:
httr::VERB(verb = "GET", url = "https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1",
httr::add_headers(`Cache-Control` = "no-cache",
`x-glb-token` = "mytoken"))
which very straightforwardly (if one has done any research before posting a question) translates to:
httr::GET(
url = "https://api.cartolafc.globo.com/auth/liga/gurudocartola-com",
httr::add_headers(
`Cache-Control` = "no-cache",
`x-glb-token` = "mytoken"
),
query = list(
`orderBy` = "campeonato",
`page` = 1L
)
)
The back-ticks are there solely to remind me they are parameters (and, they sometimes contain dashes or other chars which force a back-tick quote).

--user curl equivalent in httr

This is, I presume, some really simple curl code that I am trying to translate into a httr format.
curl -X POST \
--user '<email>:<password>' \
--header 'user-key: <user_key>' \
--url https://api.m.com/v1/clients
So far I have tried
library(httr)
POST(url = "https://api.m.com/v1/clients",
add_headers('user-key' = "userkey",
user = 'email:password'))
But without success. Any hints on what is wrong here? Is there an httr equivalent to --user in the curl code?
library(httr)
username <- 'my_user_name'
password <- 'my_password'
POST(url = "https://api.m.com/v1/clients",
config = authenticate(username, password), add_headers("Content-Type: application/json"),
body = upload_file('./my_file.json'),
encode = 'json')

Using R complete -X POST in command line tool curl

I use the command line tool curl to post data and get response from server, the command is like this:
curl -X POST -H 'Content-Type: application/gpx+xml' -H 'Accept: application/json' --data-binary #gpslog.gpx "http://test.roadmatching.com/rest/mapmatch/?app_id=MY_APPID&app_key=MY_APPKEY" -o output.json
I tried using RCurl package to do the same thing, but it doesn't work. Can someone point me to the right direction? Thanks.
postForm(uri = "http://test.roadmatching.com/rest/mapmatch/?app_id=MYID&app_key=MYKEY",
.ops = list(httpheader = c('Content-type': 'application/gpx','Accept': 'application/json')),
.params = "/Users/data.gpx")
With httr - not tested, you may have to tweak it a bit
url <- "http://test.roadmatching.com/rest/mapmatch"
args <- list(app_id = "MY_APPID", app_key = "MY_APPKEY")
gpxxml <- add_headers(`Content-Type` = "application/gpx+xml")
httr::POST(url, query = args, gpxxml, accept_json(),
write_disk("output.json"), body = upload_file("gpslog.gpx"))

Rcurl with http data post

I would like to move the following curl call to Rcurl:
curl 'http://myserver.org/stream'
-H 'Authorization: Basic XXXXXXXX' -H 'Connection: keep-alive' --data-binary '{"limit": 20}'
-H 'Content-Type: application/json;charset=UTF-8'
This is one of my R tests:
library(RCurl)
url.opts <- list(httpheader = list(Authorization ="Basic XXXXXXXX",
Connection = "keep-alive",
"Content-Type" = "application/json;charset=UTF-8"))
getURLContent('http://myserver.org/stream', .opts=url.opts)
Now I am missing an attribute to add --data or --data-binary. How to add this option?
Thanks a lot
Markus
Thanks a lot #hadley.
This is my working solution:
library(httr)
user <- "test"
password <- "test123"
POST(url = 'http://myserver.org/stream',
config = c(authenticate(user, password, "basic"),
add_headers(Connection = "keep-alive"),
accept_json()),
body = "{'username':'test'}")

Resources