5

I am planning a RESTful API and I am wondering the best way to serve files / bundles of files across the api.

I may be missing something, but as I see it my options are:

  1. Base64_encode the files and serve within the JSON response
  2. Provide links to files from within the JSON response.

I also need to bear in mind that some of these files need private and only served after successful authentication.

I have also looked at mod_xsendfile implementations briefly and wonder if this is a route I should be considering.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Mark Kendall
  • 129
  • 2
  • 10
  • 1
    What is on the other end of the api? you may need different approach for mobile / web etc. If it is an open api .. may be provide both. – d.raev Jul 25 '14 at 13:58
  • The idea is that anything may be on the end of the API although initially it is aimed at both IOS and Android apps. – Mark Kendall Jul 25 '14 at 21:03

2 Answers2

7

The world most used APIs like Facebook, Flickr and Instagram provide static links to the images.

If you provide your binary files encoded in base64 they will be heavier and it will require more CPU resources both on the server side and on the client side to encode/decode them.

The only case where there are benefits to bundle the files is if you want to send many very small files like icons.

Jan Moritz
  • 2,145
  • 4
  • 23
  • 33
2

Generally, it is a (really) bad idea to use an ASCII based protocol to transfer binary files, especially when they are heavy. You could expose an URI where the consumer will be able to download the file without using the REST API, and use a separate PHP script (or any other kind of language) to perform the access control part using sessions and output true binary data with the required HTTP Headers. The last part is pretty straightforward.

http://fr2.php.net/manual/en/function.fpassthru.php explains how to output binary data without hassle.

Hope it helps.

NaeiKinDus
  • 730
  • 20
  • 30