khernik
khernik

Reputation: 2091

Passing both a file resource and a json body in a single HTTP POST request

I'm building a REST API and I have an endpoint where I need to pass both a file resource, and a JSON body. Apparently I cannot do it:

You can only select one HTTP request method! You asked for both POST.

I'm getting this error when in cURL request I provide both form field and a body like this:

curl -X POST "http://127.0.0.1/path" -F "[email protected]" -d "@requestBody.json"

If I want this to work, I need to pass my request body as a form field itself:

curl -X POST "http://127.0.0.1/path" -F "[email protected]" -F "[email protected];type=application/json"

The thing is that in order to fetch this down the line, I need to use file_get_contents() function and then json decode the content as well. It's not a nice solution, and it seems a bit slow. Is there a cleaner way to do it?

Upvotes: 0

Views: 681

Answers (1)

brice
brice

Reputation: 1881

Depending on how big the file is, you could base64 encode the data and include that in your JSON payload.

Otherwise, you will need to use Content-Type: multipart/form-data.

Upvotes: 1

Related Questions