I'm working on a RESTful web application (Django+Piston). The POST request sends data encoded with Json to the web application. This works fine for all my text only database tables but I also have a table which stores text and binary files. What is the best way to post text and binary data to a RESTful application?
Asked
Active
Viewed 1.8k times
1 Answers
17
You can either Base64-encode it and send it as a string in a JSON message, or you can POST or PUT the binary as a separate resource and refer to it by ID or URL in the JSON message. The latter approach is a kind of out-of-band data channel that is quite common in XML-based protocols (e.g., voice chat using XMPP).
You could even quite easily support a hybrid model, whereby:
- A small image is sent as
{"base64":"OGZmNjJmOWNhYzFlODE0NDBjYmYzNjhjYz..."}
; - A large image is uploaded as a reference,
{"ref":"http://myserver.com/bits/E4304205-29B7-48EE-A359-74250E19EFC4"}
.
To avoid the double-POST needed for externally referenced binaries, you could design some protocol that allows JSON and binary stuff to be mixed in a single transfer. But the incremental gain is unlikely to adequately reward that level of effort.
Finally, from a design perspective, stick to the simple solution until it becomes a problem.

Marcelo Cantos
- 181,030
- 38
- 327
- 365
-
So if I don't want to encode the binary to a string I need two POST requests from the client side, right. First a application/json with the text fields and than a multipart/form-data to send the binary together with the ID of the data it belongs to. Is this correct? – pinky0x51 Oct 27 '10 at 10:18
-
@pinky0x51: Yes. I've amended my answer to cover this issue. – Marcelo Cantos Oct 27 '10 at 10:26
-
@pinky0x51 you could use multipart post right from the beginning sending json as one part and binary file as other – kqr Nov 08 '17 at 12:47