Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I be serving binary files (images / audio) from a RESTful api written in PHP?

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.

like image 1000
Mark Kendall Avatar asked Jul 25 '14 13:07

Mark Kendall


People also ask

What is the correct way to send a file from a REST web service to a client?

Using Postman to upload Files If you are using Postman to test your REST Services, all you need to do is create a New | HTTP request. From the HTTP Request UI: Enter the URL of the REST Service (f.e. http://localhost:8080/rest-file-manager/resr/file/upload ) Select POST as method.

How do I send a file through RESTful web services?

To attach a file, you must include it with the Body as form-data. Once you are in the Body → form-data fields, you must enter a KEY . This should be “file” or whichever value you specified in the @RequestPart(“[value]”) . After doing so, a dropdown will appear that gives you the option of Text or File.

What are the various data representation formats used by RESTful API?

When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text.


1 Answers

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.

like image 131
Jan Moritz Avatar answered Sep 29 '22 15:09

Jan Moritz