Send JSON Data in POST Request Using Curl

Sending JSON data in the body of a POST request is a fundamental task when interacting with modern web APIs. This guide demonstrates how to use the curl command-line tool to transmit JSON payloads, outlining the essential flags, headers, and syntax required for successful API communication.

The Basic Curl POST Command

To send JSON data, you must specify the HTTP method as POST, set the Content-Type header to application/json, and pass the JSON string in the data payload.

Here is the standard command-line template:

curl -X POST https://api.example.com/endpoint \
     -H "Content-Type: application/json" \
     -d '{"name": "John Doe", "email": "john@example.com"}'

Key Components Explained

Windows Command Prompt Syntax

On Windows (specifically the classic Command Prompt), the quoting rules differ. You must use double quotes to enclose the entire data payload and escape the internal double quotes with backslashes:

curl -X POST https://api.example.com/endpoint -H "Content-Type: application/json" -d "{\"name\": \"John Doe\", \"email\": \"john@example.com\"}"

(Note: If you are using PowerShell on Windows, the standard Linux-style single-quote syntax will work).

Sending JSON From a File

If you are dealing with a large or complex JSON payload, it is often easier to save the JSON to a file (e.g., data.json) and reference it in your command.

Use the @ symbol followed by the file path to upload the file contents:

curl -X POST https://api.example.com/endpoint \
     -H "Content-Type: application/json" \
     -d @data.json