Matt
Matt

Reputation: 5168

Is there a way to pass the content of a file to curl?

I would like to execute a fairly complex HTTP request with multipart/mixed boundaries from the command line.

POST /batch HTTP/1.1
Host: www.googleapis.com
Content-length: 592
Content-type: multipart/mixed; boundary=batch_0123456789
Authorization: Bearer authorization_token

--batch_0123456789
Content-Type: application/http
Content-ID: <item1:[email protected]>
Content-Transfer-Encoding: binary


POST /drive/v2/files/fileId/permissions
Content-Type: application/json
Content-Length: 71


{
  "role": "reader",
  "type": "user",
  "value": "[email protected]"
} 


--batch_0123456789
Content-Type: application/http
Content-ID: <item2:[email protected]>
Content-Transfer-Encoding: binary


POST /drive/v2/files/fileId/permissions
Content-Type: application/json
Content-Length: 71


{
  "role": "reader",
  "type": "user",
  "value": "[email protected]"
}


--batch_0123456789--

Ideally I would like to put this request into a file and then simply call curl to execute that HTTP request.

curl myrequest.txt

Is there any easy straightforward way of doing this? I understand that there are client libraries that have their idiomatic ways of handling this, but I am interested to find out if there is a way to do this from the command line.

Upvotes: 3

Views: 1826

Answers (1)

TachyonVortex
TachyonVortex

Reputation: 8572

You can use the --config option (see the "CONFIG FILE" section of the manual for more details):

curl --config myrequest.txt

I don't think there's a clean way to embed a multiline POST body within the config file. You could replace each newline character with \r\n (CRLF newlines are required for multipart requests):

url = "http://www.googleapis.com/batch"
header = "Content-length: 592"
header = "Content-type: multipart/mixed; boundary=batch_0123456789"
header = "Authorization: Bearer authorization_token"
data-binary = "--batch_0123456789\r\nContent-Type: application/http\r\nContent-ID: <item1:[email protected]>\r\nContent-Transfer-Encoding: binary\r\n\r\n..."

but that's not very easy to read.

Alternatively, you could put the POST body in a separate file. For example:

myrequest.txt

url = "http://www.googleapis.com/batch"
header = "Content-length: 592"
header = "Content-type: multipart/mixed; boundary=batch_0123456789"
header = "Authorization: Bearer authorization_token"
data-binary = "@myrequestbody.txt"

myrequestbody.txt

--batch_0123456789
Content-Type: application/http
Content-ID: <item1:[email protected]>
Content-Transfer-Encoding: binary


POST /drive/v2/files/fileId/permissions
Content-Type: application/json
Content-Length: 71

...

Upvotes: 2

Related Questions