Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for RESTFull Web services and file download

Tags:

rest

I'm currently working on a RESTFull application that can provide the clients generated binary files. I'm wondering what would be the best practice :

  • Send a GET request to the application, generate the file and write to the response, with the correct headers ?
  • Send a GET request to the application, generate the file and write json data containing the file metadata and a link to a download servlet ?
like image 385
Jib'z Avatar asked Oct 23 '15 15:10

Jib'z


2 Answers

My use case was that we might be creating a really large file, the creation process might take a while. Also, I do not want my file creation process to be interrupted as it will surely be costly to do so. So, a good solution seems to be async file generating with signaling.

Steps:

  1. create a new file, POST /downloads (endpoint name an example), response 202 Accepted, Location: /downloads/123 (unique ID of the download). If we're sharing the files among users, the same POST might return the same ID (all the users are waiting for the same file to generate)
  2. request the file, GET /downloads/123, file not yet completed, response 102 Processing (and an optional progress and/or ETA, if available)
  3. request the file, GET /downloads/123, file completed, response 303 See other, Location: https://cdn/full-path-to-generated.file.pdf

It enables you to create really large files and take a really long time, reuse the file creation process for multiple users and also transfer the file generation process itself off form the app server to a worker.

like image 88
Dalibor Karlović Avatar answered Oct 19 '22 02:10

Dalibor Karlović


I would say the first approach but it depends on what you want to return as metadata. As a matter of fact, you can leverage the Content-Disposition header to send back metadata like filename, ...

You can also notice that it's also possible to send back to the client a multipart content. This allows to mix file contents and form data.

Hope it helps you.

like image 42
Thierry Templier Avatar answered Oct 19 '22 02:10

Thierry Templier