How do I POST JSON data with cURL?

To POST JSON data using cURL, use the -H flag to set the Content-Type header to application/json and the -d/--data flag to include the JSON payload. Here’s how to do it:

Basic Command

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"key": "value", "nested": {"data": true}}' \
  https://api.example.com/endpoint

Key Options

  • -X POST: Explicitly sets the HTTP method to POST (optional if using -d).
  • -H "Content-Type: application/json": Specifies the request body is JSON.
  • -d '{"key": "value"}': Provides the JSON payload (use single quotes to avoid shell escaping issues).

Send JSON from a File

For large JSON payloads, read from a file:

curl -X POST \
  -H "Content-Type: application/json" \
  --data-binary @data.json \
  https://api.example.com/endpoint
  • @data.json: Loads JSON from the file data.json.

Include Headers (e.g., Authentication)

curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{"query": "test"}' \
  https://api.example.com/secure

Handle Responses

  • Print response headers: Add -i.
  • Save output to a file: Add -o response.json.
  • Verbose mode: Add -v for debugging.

Example:

curl -X POST -i \
  -H "Content-Type: application/json" \
  -d '{"status": "ok"}' \
  -o response.json \
  https://api.example.com/endpoint

Common Errors

  1. Syntax Issues:
  • Use single quotes (') around JSON to avoid shell expansion.
  • Validate JSON with tools like JSONLint.
  1. Missing Headers:
  • Ensure Content-Type: application/json is included.
  1. Escaping Special Characters:
  • For complex JSON, escape double quotes with \ or use a file:
    bash -d "{\"key\": \"value\"}"

Example Workflow

  1. Create a JSON file (payload.json):
   {
     "name": "Alice",
     "age": 30,
     "active": true
   }
  1. Send the request:
   curl -X POST \
     -H "Content-Type: application/json" \
     --data-binary @payload.json \
     https://api.example.com/users

Verify with Tools

Test your endpoint first with tools like:

  • Postman
  • httpie (e.g., http POST https://api.example.com/endpoint < data.json).

This method works for APIs, webhooks, and services expecting JSON input. Always check the API documentation for specific requirements!

Leave a Reply

Your email address will not be published. Required fields are marked *