rstudio / plumber

Turn your R code into a web API.
https://www.rplumber.io
Other
1.39k stars 256 forks source link

Return content-type with filename #287

Closed aleDsz closed 5 years ago

aleDsz commented 6 years ago

Hi,

I'm using the serializer with contentType to return a CSV. But my customer asked me for return this CSV with a file name, but i didn't find anything about returning with a filename, using plumber package.

#* @serializer contentType list(type="text/csv")
#* @get /get_report
api.get_report <- function (req) {
    [...]
}

There's a way to do that, or this feature is in the dev pipeline?

Thanks, aleDsz.

schloerke commented 6 years ago

Is the goal to:

?


If you need the file name as well as the content, from the user's perspective, it should be a dynamic route that is resolved with api.get_report.

#* @serializer contentType list(type="text/csv")
#* @get /get_report/<file_name>.csv
api.get_report <- function (file_name) {
    [...]
# return csv content
}

If I visited /get_report/my_file.csv I could save the content as is (with .csv in the url).

Does this answer your question?

ssword commented 6 years ago
#* @serializer contentType list(type="text/csv")
#* @get /get_report/
api.get_report <- function () {
  ...
  ...
  # This header is a convention that instructs browsers to present the response
  # as a download named filename rather than trying to render it inline.
  attachmentString = paste0("attachment; filename=", filename)

  res$setHeader("Content-Disposition", attachmentString)

  # Read in the raw contents of the binary file
  bin <- readBin(outputfile, "raw", n=file.info(outputfile)$size)

  #Return the binary contents
  bin
}

filename is the name of the file outputfile is the path to the file Maybe like this? It will return the file with specific name, meanwhile, have file name information in the header.

schloerke commented 6 years ago

Please let me know if you come to a solution for this one. The header looks promising.

trestletech commented 6 years ago

Example docs proposed here: https://github.com/trestletech/apis-plumber/pull/14/files

jimjam-slam commented 5 years ago

I can see that it's possible to add a custom or dynamically generated default file name for downloads by setting the bypassing serialization (ie. by doing the serialization work, like setting the headers and body, in the endpoint) and returning the response object.

But I can see that image serializers (png and jpeg) accept custom arguments, like width and height. It'd be great if I could do the same for my own serializers. Is it possible to do so and either:

The second scenario is particularly attractive to me—my users request a CSV file from an endpoint based on a number of input arguments, and it would be great if the CSV served to them had a default file name reflecting those inputs.