Plumber: return xlsx or csv files

Created on 16 Nov 2018  路  6Comments  路  Source: rstudio/plumber

Hi,

My code takes in an input csv and is supposed to output another csv or xlsx. I tried using XLSX content type from https://github.com/trestletech/plumber/blob/master/R/content-types.R, but it is throwing an exception every time without any mention about the exception type. Is there a way to do this?

help wanted question

Most helpful comment

Thanks a lot @shrektan!! It works perfectly.

All 6 comments

@Amalabdu Would you mind provide a minimal reproducible example? I'm not sure what your problem is.

If we have to return a PDF file then we use something like

* @serializer contentType list(type="application/pdf")

* @get /pdf

function(){
tmp <- tempfile()
pdf(tmp)
plot(1:10, type="b")
text(4, 8, "PDF from plumber!")
dev.off()

readBin(tmp, "raw", n=file.info(tmp)$size)
}

Now what if I want to return a CSV file? As in there is a model that runs and outputs a CSV. So can we output a CSV through Plumber, using XLSX or otherwise?

@Amalabdu The example code below should solve your problem. It works for me.

BTW, using three backticks (```) to enclose the code makes your code easier to read.

The hosting code

serializer_csv <- function(){
  function(val, req, res, errorHandler){
    tryCatch({
      res$setHeader("Content-Type", "text/plain")
      res$setHeader("Content-Disposition", 'attachment; filename="xxx.csv"')
      res$body <- paste0(val, collapse="\n")
      return(res$toResponse())
    }, error=function(e){
      errorHandler(req, res, e)
    })
  }
}
plumber::addSerializer("csv", serializer_csv)
plumber::plumber$new("plumber-csv.R")$run(port = 8833)

The plumber-csv.R file

#* @serializer csv
#* @get /csv
function() {
  df <- data.frame(CHAR = letters, NUM = rnorm(length(letters)), stringsAsFactors = F)
  csv_file <- tempfile(fileext = ".csv")
  on.exit(unlink(csv_file), add = TRUE)
  write.csv(df, file = csv_file)
  readLines(csv_file)
}

References

Thanks a lot @shrektan!! It works perfectly.

The code below:

plumber::addSerializer("csv", serializer_csv)

...throws an error if it's done a second time "Already have a serializer by the name of csv".

How can I check the serializers first to see if this exists, or enforce it to be overridden?

Locking thread. Please open a new issue referencing this one for context.

@willwright76 Thank you for the issue! I have added it in #410

Was this page helpful?
0 / 5 - 0 ratings

Related issues

daxilshah picture daxilshah  路  4Comments

meztez picture meztez  路  4Comments

elbamos picture elbamos  路  6Comments

jeffkeller87 picture jeffkeller87  路  6Comments

Jube-Dev picture Jube-Dev  路  3Comments