Saugat Awale
Saugat Awale

Reputation: 21

How can I send a $http.delete() request for this RESTful implementation?

This is my PHP code.

<?php

    header("Content-Type: application/json");
    // get the HTTP method, path and body of the request
    $method = $_SERVER['REQUEST_METHOD'];
    $request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
    var_dump($request);
    $input = json_decode(file_get_contents('php://input'),true);

    // connect to the mysqli database
    $link = mysqli_connect('localhost', 'root', 'hello', 'agita');
    mysqli_set_charset($link,'utf8');

    // retrieve the table and key from the path
    $table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
    $key = array_shift($request)+0;

    // escape the columns and values from the input object
    $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
    $values = array_map(function ($value) use ($link) {
      if ($value===null) return null;
      return mysqli_real_escape_string($link,(string)$value);
    },array_values($input));

    // build the SET part of the SQL command
    $set = '';
    for ($i=0;$i<count($columns);$i++) {
      $set.=($i>0?',':'').'`'.$columns[$i].'`=';
      $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
    }

    // create SQL based on HTTP method
    switch ($method) {
      case 'GET':
        $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
      case 'PUT':
        $sql = "update `$table` set $set where id=$key"; break;
      case 'POST':
        $sql = "insert into `$table` set $set"; break;
      case 'DELETE':
        $sql = "delete `$table` where id=$key"; break;
    }

    // excecute SQL statement
    $result = mysqli_query($link,$sql);

    // die if SQL statement failed
    if (!$result) {
      http_response_code(404);
      die(mysqli_error());
    }

    // print results, insert id or affected row count
    if ($method == 'GET') {
      if (!$key) echo '[';
      for ($i=0;$i<mysqli_num_rows($result);$i++) {
        echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
      }
      if (!$key) echo ']';
    } elseif ($method == 'POST') {
      echo mysqli_insert_id($link);
    } else {
      echo mysqli_affected_rows($link);
    }

    // close mysqli connection
    mysqli_close($link);
?>

I have implemented a RESTful API, now I can receive the JSON object with the $http.get(url+customerId). This will return me the JSON object I want. Looking at the above server code what is the call I need to back for instance if I wanted to delete a customer with customerId 5?

I tried $http.delete(url+customerId).then()...

But It does not seem to work. Help needed.

Upvotes: 0

Views: 510

Answers (2)

Cherian M Paul
Cherian M Paul

Reputation: 656

I used the same script.

The problem here is this line of code:

  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;

It needs to be updated to following code:

  case 'DELETE':
    $sql = "delete FROM `$table` where id=$key"; break;

Now run the code and it will work. It worked for me.

Here is the link to the actual code:

https://www.leaseweb.com/labs/2015/10/creating-a-simple-rest-api-in-php/

Thanks,

Cherian.

Upvotes: 0

Christoph Kappestein
Christoph Kappestein

Reputation: 421

Take a look at the browser developer console to see what the script returns. Since you say it returns a 500 I would assume that PHP crashes. From what I see the mysqli_error misses the $link as parameter. But the error log should contain a detail message.

A few hints to your script:

  • I would use prepared statments instead of mysqli_real_escape_string
  • You could use the json_encode function to always return a proper JSON response. I.e. maybe you can simply use: json_encode($result->fetch_all(MYSQLI_ASSOC)) to output the response on GET.
  • I would return a 500 status code instead of 404 in case of an error
  • You should use 404 only in case an entry does not exist $result->field_count == 0

Iam also the developer of Fusio an open source project which tries to simplfies building APIs like in your script. If you like you can check it out at: http://www.fusio-project.org/

Upvotes: 1

Related Questions