4

I am creating a REST API on top of an existing application. One of the features takes in a json data along with a file uploaded by the user.

I am unsure how to send a file AND json data in the same request to the REST API?

I have the json part working and I test that using curl:

curl -XPOST http://localhost:8080/myapp/foo -d '{"mydata": {
    "name": "somename",
    "gender": "male"
}}'
//I would like to send an image (say, profile image) with the above request as well.

I'm using a grails application so I get this data in my controller like so: new Foo(params.mydata).

Question

  • Is it possible to send JSON data and a file in the same request to the API? If so, how can I do it using curl or REST Console (chrome extension)
  • What would be the contentType of this request?
  • I'm open to sending data in another format if it means that I can send file and other data (strings) within the same request. I'm not tied on JSON

Update

I found another SO question which is asking the same thing. From the answer to that question it seems there are only three choices and none of which say that its possible to send both, json data and file, within the same request. Which is very discouraging...I will keep this question open to see if anyone has other ideas.

Community
  • 1
  • 1
birdy
  • 8,476
  • 22
  • 98
  • 170

1 Answers1

2

I think the "right" way to do this is with a multipart message. That way, you can post up both the JSON and the Image with their corresponding correct MIME type. The wikipedia article on multipart mime types has an example of what this would look like. It looks like both Apache httpcommons and Jersey support this sort of thing, and apparently curl does too!

Community
  • 1
  • 1
David
  • 2,456
  • 1
  • 14
  • 29
  • I am confused. Your answer is encouraging but I found another SO question which is along the same lines as my question and it seems there are only three choices available. None of which say that json data and a file can be sent in same request: http://stackoverflow.com/questions/4083702/posting-a-file-and-data-to-restful-webservice-as-json – birdy May 14 '13 at 19:06
  • 2
    I was about to suggest what amounts to option 3 in the link you posted - send the metadata, server responds with a URI to post the image to, send the image to that URI. However multipart/mixed MIME type lets you have multiple content types in the same message, separated by whatever "boundary" you define. That would make the overall content type = multipart/mixed, then the next two blocks are application/json, then image/jpeg. – David May 14 '13 at 19:20
  • ok, let me try the `multipart/mixed` content type with two blocks `application/json` and `image/jpeg`. Wait, how will the second block `image/jpeg` work? Will the file be uploaded? Just trying to figure out how to send this request as test with REST Console Chrome plugin :) – birdy May 14 '13 at 19:26