I am trying to receive data from an API based on the data I will send to it using PHP.
Forexample: I connect to API and send it bookId = 3, the API sends a response isPurchased = true.
API:
This is what I want to achieve using PHP. This is what I do in Postman.
Connect to the API's URL.
Using POST, send a request by Entering bookId.
{bookId : 2}
This is the response I get from the API.
{
bookId : 2,
isPurchased : true,
bookTitle : 'War and Peace'
}
I want to achieve the exact same process in PHP.
I have the following code so far. I am not sure how I can achieve my purpose.
Any help is greatly appreciated.
PHP:
<?php
$isPurchased = false;
$bookId = 2;
// Call API:
$ch = curl_init();
$url = "https://myapi.com/books";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,"bookId=".$bookId);
//bookId is from API and $bookId is from user. - I am not sure if this is how you send the
//info to the API but this is how I have seen it done in a tutorial.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
$obj = json_decode($json);
//print_r($obj);
if ($obj->{'isPurchased'} == true)
{
$isPurchased = TRUE;
}
curl_close ($ch);
?>
When I run this code, I don't receive anything from the API. Am I doing something wrong?
Again, any help with this would be much appreciated.
If there is any other, easier method, I am more than willing to give it a go.