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”:[“recipient1@gmail.com”, “recipient2@gmail.com”]}

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":["recipient1@gmail.com", "recipient2@gmail.com"]};
$url = "http://api.domain.com/api/send_email_attachment.php";
$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);
curl_close($curl);

.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s