Serve and Consume API that requires a JSON and not POST Fields

In PHP, $_POST would give you the POST payload. I was trying to post a multi-dimentional JSON to an API but the $_POST wasn’t able to get data for a field that had a list of values within,

e.g. {“email_recipients”:[“”, “”]}

Therefore, I had to write the API so it accepts a JSON which can be read into the API and converted to an array as follows:

$post_json = file_get_contents("php://input");
$array_post_data = json_decode($post_json, true);

Now, the client CURL call would appear something like this:

$json = {"email_recipients":["", ""]};
$url = "";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
$response = curl_exec($curl);
$curl_error = curl_error($curl);


Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s