Curl POST Request Body From Local File
This article explains how to use the curl command-line
tool to send a POST request using data stored in a local file as the
request body. You will learn the correct syntax for importing text,
JSON, and binary files directly into your API calls, along with examples
for setting the appropriate headers.
To instruct curl to read the POST request body from a
local file, you must use the @ symbol followed by the file
path in combination with either the -d
(--data) option or the --data-binary
option.
Method 1: Using
the -d Option (For Text and JSON)
For standard text data, such as JSON or XML, use the -d
or --data option. The @ prefix tells
curl that the string following it is a file path rather
than the actual data payload.
curl -X POST -H "Content-Type: application/json" -d "@data.json" https://api.example.com/endpointIn this example: * -X POST specifies the request method.
* -H "Content-Type: application/json" tells the server to
expect JSON data. * -d "@data.json" instructs
curl to read the contents of the local file named
data.json and use it as the request body.
Note: When using -d, curl strips carriage returns
and newlines from the file content.
Method
2: Using the --data-binary Option (For Exact Preservation
or Binary Files)
If you need to preserve the exact formatting of your file, including
newlines, carriage returns, or if you are uploading a non-text binary
file (such as an image or a compressed archive), use the
--data-binary option.
curl -X POST -H "Content-Type: application/octet-stream" --data-binary "@archive.zip" https://api.example.com/uploadIn this example: * --data-binary "@archive.zip" posts
the exact binary data of archive.zip without any processing
or modification.
File Path Specifications
You can use relative or absolute paths to reference your local file:
- Relative path:
-d "@data.json"(looks for the file in your current working directory) - Subdirectory path:
-d "@config/payload.json" - Absolute path:
-d "@/Users/username/desktop/payload.json"