cURL by Example: JSON Payload
Send JSON data. This example demonstrates how to properly format and send a JSON object in a POST request, ensuring the server interprets it correctly.
Code
# Sending JSON data via POST
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "[email protected]"}'
# Reading JSON from a file
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @data.json
# PUT request with JSON
curl -X PUT https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"active": true}'Explanation
When interacting with modern REST APIs, JSON (JavaScript Object Notation) has become the de facto standard for data exchange. To send JSON data correctly, you must set the Content-Type header to application/json so the server knows to parse the request body as JSON rather than other formats like form data or XML. The -d flag (or --data) is used to provide the JSON payload. When you use -d, cURL automatically changes the request method to POST (unless you explicitly specify otherwise with -X) and sets a default Content-Type of application/x-www-form-urlencoded, which is why explicitly setting application/json is crucial.
Shell quoting is a critical consideration when working with JSON data. It is important to use single quotes ('...') around the JSON string in Unix-like shells (bash, zsh, etc.) to prevent the double quotes inside the JSON from being interpreted or removed by the shell. The shell treats everything inside single quotes as literal text. On Windows Command Prompt, the quoting rules differ: you typically need to use double quotes for the outer wrapper and escape inner double quotes with backslashes or use PowerShell which has different escaping rules. For cross-platform compatibility and readability, many developers prefer to store JSON in external files.
For larger payloads, complex nested JSON structures, or when working in automated scripts, it is significantly cleaner and more maintainable to save the JSON to a file and reference it using the @filename syntax (e.g., -d @data.json). The @ symbol tells cURL to read the data from the specified file rather than treating it as a literal string. This approach completely avoids shell escaping issues, makes the command more readable, allows for better version control of test data, enables easy editing of the JSON in a proper editor with syntax highlighting, and facilitates reuse of the same payload across multiple requests. You can also use -d @- to read from standard input, enabling piped commands.
Code Breakdown
-H "Content-Type: ..." is crucial for the server to parse JSON.-d @data.json reads the request body from a local file.
