REST API Design sends JSON data and file in api in the same request

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

I'm not sure how to send the AND json file to the same REST API request?

I have a json part and I verify that with 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 use the grails application, so I get this data in my controller as follows: new Foo(params.mydata) .

Question

  • Is it possible to send JSON data and a file to the same API request? If yes, how to do it using curl or REST Console (chrome extension)
  • What will be the contentType this request?
  • I am open to sending data in a different format, if this means that I can send the file and other data (rows) to the same request. I am not tied to JSON.

Update

I found another SO question that asks the same thing. From the answer to this question, it seems that there are only three options, and none of them says that it can be sent as json-data, as well as a file in the same request. This is very discouraging ... I will keep this question open to find out if anyone has any other ideas.

+4
source share
1 answer

I think the β€œright” way to do this is with a multi-page post. This way you can publish both JSON and Image with the corresponding correct MIME type. The wikipedia article on multi-user mime types has an example of how this would look. Both Apache httpcommons and Jersey seem to support such things, and apparently curl too!

+2
source

Source: https://habr.com/ru/post/1480784/


All Articles