0

I have created a dummy model using the below code :

#get the data
data(Boston, package="MASS")

# train a model for median house price as a function of the other variables
bos_rf <- lm(medv ~ crim + indus + dis , data=Boston)

# save the model
saveRDS(bos_rf, "bos_rf.rds")

Now i want to expose this model as an API using plumber. For this my code is

# load as bos_rf.R

bos_rf <- readRDS("bos_rf.rds")

#* @param input_json JSON file
#* @post /score
function(input_json)
{
  temp <- toJSON(input_json, auto_unbox = T)
  data <- fromJSON(temp) %>% as.data.frame
  data = data %>% mutate_all(as.numeric)
  predict(bos_rf, data)
}

Above my param is a JSON , i am keen to actually keep it as a data frame . I am converting the JSON to data frame in the function

Then i start the API using

# try API 1 
# 
dummy_model_api <- plumber::plumb("2_R_code_to_API.R")
dummy_model_api$run(host = '127.0.0.1', port = 8000)

API runs fine when i paste the JSON in the swagger portal , but when i run curl using below commands

$ curl "http://127.0.0.1:8000/score" -d "@test.JSON"
$ curl --data @test.json http://localhost:8000/score

None work. how do i directly pass the test JSON to the API to get a prediction. Note that if i check the function with R i get the prediction. Kindly advise how can one pass a JSON or DF directly to curl API request and get a response vs manually copying json / or defining API inputs with each variable one by one. Such a method is not feasible with 100's of variables.

How can a sample of this JSON also reflect in the swagger body already. i.e. above when the swagger opens , a sample JSON is already there in body with some values and ready to execute.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Learner_seeker
  • 544
  • 1
  • 4
  • 21

1 Answers1

0

plumber will execute fromJSON on the request body if it dectects it starts with {.

What you would normally do is send a JSON string like

{
  "input_json" : _insert toJSON results here_
}

So that plumber can turn that into a named list and map input_json to your function parameter.

Bruno Tremblay
  • 756
  • 4
  • 9