Posting JSON data to API using CURL

Posting JSON data to API using CURL

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Critical Mismatch Between JSON Payloads and URL Parameters

When attempting to send an email invitation via a REST API using curl, the most common stumbling block isn't network latency or DNS resolution; it is how the data format is transmitted versus what the server expects. In the scenario described, the developer constructs a valid JSON string using json_encode() but inadvertently passes it in a way that breaks the request entirely.

The core issue lies in the sendPostData function definition. Specifically, look at this line:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

The function accepts $str_data, which is already a JSON string (e.g., [{"authorizedKey": "..."}, ...]). However, http_build_query() expects an associative array of key-value pairs and converts them into a query string format like key1=value1&key2=value2. When you pass a raw JSON string into http_build_query(), PHP attempts to interpret the string characters as keys and values. This results in malformed data being sent to the server, often appearing as a single blob or causing a syntax error on the receiving end.

To fix this, you must align the client-side encoding with the API's documentation. The provided API reference indicates that SendInvitation expects a JSON payload. Therefore, the CURLOPT_POSTFIELDS option should receive the raw JSON string directly, without any transformation. Additionally, the Content-Type header must explicitly tell the server that the body contains JSON.

Here is the corrected implementation for a raw PHP script:

$url = 'http://api.address.com/SendInvitation'; // Ensure trailing slashes are handled correctly per API spec
$jsonPayload = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Pass the raw JSON string directly, do not use http_build_query()
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload); 
// Inform the server of the content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json'
));

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($response === false) {
    echo 'cURL Error: ' . curl_error($ch);
} else {
    echo "Response Status: $httpCode\n";
    echo "Response Body:\n$response";
}

There is a subtle but often overlooked detail in the original code snippet: the trailing question mark in $url_send. The variable is defined as http://api.address.com/SendInvitation?. In many API designs, a leading ? without any parameters immediately following it can be interpreted differently than no query string at all. If the API endpoint does not expect query parameters and receives them anyway, it might reject the request or return a 400 Bad Request error. It is best practice to trim trailing question marks unless specific GET parameters are required.

Why curl_exec Might Appear Silent

The original complaint mentions "not getting any output." This usually stems from one of two causes: silent errors or missing output buffering.

First, if the API returns an HTTP 204 No Content or 200 OK with an empty body (common for invitation APIs that simply acknowledge receipt), $response will be an empty string. If you are not echoing the result or checking the HTTP status code, it looks like nothing happened. Always inspect curl_getinfo($ch, CURLINFO_HTTP_CODE) to verify the request was accepted before assuming failure.

Second, if using a web framework context rather than a CLI script, ensure that output buffering isn't interfering with your debug prints. However, in a standalone script or Laravel controller returning raw JSON, the response should be visible immediately upon execution.

Handling the Response

When sending an invitation, the server might return a success token or a job ID rather than the full email details. For example, the API might respond with:

{
    "success": true,
    "jobId": "a1b2c3d4",
    "message": "Invitation sent successfully"
}

If your application expects to parse this data, ensure you decode the response back into an array using json_decode($response) rather than treating it as a string. This allows you to extract the jobId for tracking purposes or handle potential error messages contained in the response body.

Best Practices for API Integration

When integrating with external services like PayQuicker, always consult the official documentation to determine if the endpoint supports JSON, XML, or form-encoded data. The provided link confirms that POST-api-SendInvitation expects a JSON body. Mixing formats—sending a JSON string but treating it as URL parameters—is the primary cause of "silent failures" where no error message is returned because the server simply fails to parse the input correctly.

For production applications, consider using a framework like Laravel, which handles cURL configurations and response parsing automatically through its HTTP client. This reduces the risk of misconfigured headers or incorrect payload encoding. If you require advanced features like retry logic or authentication handling within your API calls, leveraging an established library ensures consistent behavior across different environments.

Our network