55

We are extending our HTTP REST API to allow clients to upload picture (for the purpose of this question, assuming binary data). So far we have only allowed simply strings in our API parameters. What is a good way to allow them to upload binary data? Would it be to request for the base64 encoded form? Would the URL become too long for the web server to handle?

Any suggestions/best practices?

Henke
  • 1,466
  • 2
  • 9
  • 22
erotsppa
  • 14,959
  • 29
  • 109
  • 164

1 Answers1

52

Just send the binary data as-is in a POST body, but with the appropriate Content-Type header (e.g. image/jpeg) - I think this is the most "RESTful" way.

(In general, as a rule of thumb when designing REST services, the more you work with the HTTP protocol as-is instead of trying to overlay something unnecessary and complex on top of it like base64, the better. HTTP is the ultimate RESTful protocol, and Content-Types allow for different "Representations" in "REpresentational State Transfer")

Another possibility to keep in mind is accepting image URLs instead of actual physical files. This makes it harder for standalone apps that e.g. read the image off the user's drive, but make it easier for mashup-type apps where the image may be returned as a URL from another service.

You can allow both options of course.

Eugene Osovetsky
  • 6,212
  • 2
  • 36
  • 58
  • 2
    What content-type should we use for custom binary data that are not jpeg images? – Pacerier Jul 04 '12 at 06:08
  • should you add the Content-Length header on the response when people try to retrieve the image? – Cmag Aug 13 '14 at 16:32
  • Most HTTP stacks I've seen automatically set Content-Length when it is required by the HTTP protocol. (It shouldn't always be there, e.g. in streaming mode... don't remember the exact details, take a look at the HTTP RFC if you're interested. Best to let the underlying stack to deal with it for you.) – Eugene Osovetsky Aug 13 '14 at 21:12
  • @Pacerier for generic binary data use application/octet-stream – Steven Sep 22 '20 at 04:33