duraq
duraq

Reputation: 119

API that takes a file as input parameter

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 ?

Upvotes: 3

Views: 1645

Answers (1)

alko989
alko989

Reputation: 7928

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 [email protected] http://localhost:1234/uploadfile

Upvotes: 3

Related Questions