0

There seems to be an issue with the API handling JSON input. This is my API (Delete function)

function doDeleteCustomer() {
global $db;
if(isParamSet(array('id'))) {
    if(isParamAvailable(array('id'))) {
        $customerId = $_REQUEST['id'];
        $sql = "DELETE FROM customers WHERE ID=:customerid";
        $stmt = $db->prepare($sql);
        $stmt->execute(
            array(
                ':customerid' => $customerId
            )
        );
        if($stmt->rowCount() > 0) {
            $response = array();
            $response["error"] = false;
            $response["status"] = 200;
            $response["data"] = array();
            $response["message"] = "Successfully removed customer!";
        } else {
            $response = array();
            $response["error"] = true;
            $response["status"] = 400;
            $response["data"] = array();
            $response["message"] = "Unable to remove customer!";
        }
        return json_encode($response);
    }
}

}

When I test it in Postman everything works fine, but I have provide the information in x-www-form-urlencoded.

enter image description here

But when I want to give the input by raw JSON data I get a message that the required id field is missing...What am I doing wrong?

enter image description here

Sonia
  • 195
  • 1
  • 3
  • 12

2 Answers2

3

You have to use json_decode before processing your data if you intend to make your application accept json. Alternatively, if you'd like it to support both, you could use try catch in order to switch.

More information about json_decode can be found here and here.

Zirc
  • 460
  • 3
  • 14
  • Thank you for your reply. As I'm a noobie and still very much learning API. Where do I need to put the json_decode? – Sonia May 07 '20 at 15:36
  • I haven't touched PHP in a long time, but... From what I understand, `$_REQUEST` is the variable that will receive the body of the request... Therefore, if it is receiving JSON it will be something like this `$_REQUEST = '{"a":1,"b":2,"c":3,"d":4,"e":5}';` If you notice, the variable will equate to a string... so you need to use json_decode in order to turn it into an object/dictionary/hashmap (whatever you call it) in order to process it... so I believe you need to put `json_decode($_REQUEST)` before the if statement, then check whether `id` is present in the request body message – Zirc May 07 '20 at 15:44
0

I have found it, thanks to the this from Zirc.

All I needed to do was $_REQUEST = json_decode(file_get_contents('php://input'), true); before the first if statement

Sonia
  • 195
  • 1
  • 3
  • 12