0

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.

  1. Connect to the API's URL.

    https://myapi.com/books

  2. Using POST, send a request by Entering bookId.

    {bookId : 2}

  3. 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.

mrkn0007
  • 135
  • 1
  • 1
  • 11
  • 1
    Start by adding a call to [curl_error()](https://www.php.net/manual/en/function.curl-error.php) and seeing if there is in fact some help available – RiggsFolly Oct 19 '21 at 14:48
  • ok, will give it a go. – mrkn0007 Oct 19 '21 at 14:50
  • `"bookId=".$bookId` isn't the same as `{bookId : 2}` which you mentioned as using in the PostMan. One's form-url-encoded data, the other is JSON. Which one does the API accept? What content-type header did you select in the Postman? – ADyson Oct 19 '21 at 14:54
  • 1
    P.S. You know that Postman can auto-generate PHP/Curl code from the details of your postman request...? – ADyson Oct 19 '21 at 14:54
  • My API accepts JSON and I will try the Postman's auto generated Curl data. – mrkn0007 Oct 19 '21 at 14:59
  • 1
    `My API accepts JSON`...well then you need to send JSON data from curl, obviously. https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl – ADyson Oct 19 '21 at 15:10

0 Answers0