PHP CURL Using POST Raw JSON Data
If you wanna use Content-type: application/json
and raw
data, seem your data should be in json
format
$ch = curl_init();
$headers = [
'x-api-key: XXXXXX',
'Content-Type: text/plain'
];
$postData = [
'data1' => 'value1',
'data2' => 'value2'
];
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
If you want an arranged and explained format, see the code below.
// Set The API URL
$url = 'http://www.example.com/api';
// Create a new cURL resource
$ch = curl_init($url);
// Setup request to send json via POST`
$payload = json_encode(array(
'data1' => 'value1',
'data2' => 'value2'
)
);
// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-api-key: XXXXXX', 'Content-Type: application/json'));
// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request
$result = curl_exec($ch);
// Get the POST request header status
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// If header status is not Created or not OK, return error message
if ( $status !== 201 || $status !== 200 ) {
die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}
// Close cURL resource
curl_close($ch);
// if you need to process the response from the API further
$response = json_decode($result, true);
I hope this helps someone