3

I’ve been asked to create an API that takes a file as input and places that file in a directory on a server. This is to take away the need for an app to interact with the folder directly.

I’ve built APIs before (using Plumber in R) and can deal with string inputs - I’m just stumped on taking a file as input parameter. None of the plumber documentation explains how to do this. Can this even be done ? Is there a way to do this in Python ?

duraq
  • 99
  • 1
  • 12
  • I think you can just call `httr::POST()` with the server location and the file in the `body` argument - check out the documentation for specific examples. – Mako212 Sep 23 '19 at 18:06
  • And the Python module `requests` would let you do the same thing. – Mako212 Sep 23 '19 at 18:09

1 Answers1

3

You can use plumber and Rook to upload files using POST.

Here is a small example

api.R

library(plumber)
library(Rook)

#* Upload file
#* @param upload File to upload
#* @post /uploadfile
function(req, res){
  fileInfo <- list(formContents = Rook::Multipart$parse(req))
  ## The file is downloaded in a temporary folder
  tmpfile <- fileInfo$formContents$upload$tempfile
  ## Copy the file to a new folder, with its original name
  fn <- file.path('~/Downloads', fileInfo$formContents$upload$filename)
  file.copy(tmpfile, fn)
  ## Send a message with the location of the file
  res$body <- paste0("Your file is now stored in ", fn, "\n")
  res
}

Run server

plumber::plumb('api.R')$run(port = 1234)

Send file test.txt using curl

curl -v -F upload=@test.txt http://localhost:1234/uploadfile
alko989
  • 7,688
  • 5
  • 39
  • 62
  • 1
    This is great - thank you very much. Got it working in Python but prefer to do this is in R. Thanks ! – duraq Sep 24 '19 at 18:46