PHP : REST API – DELETE data using cURL

The HTTP DELETE method asks the API to remove a record. Like PUT, the id of the record is written in the URL. If you are new to cURL, read GET data using cURL first.


Delete data with DELETE

We delete the post with id 1, using the endpoint https://jsonplaceholder.typicode.com/posts/1.

<?php
$url = "https://jsonplaceholder.typicode.com/posts/1";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if ($response === false) {
    die("cURL error: " . curl_error($ch));
}

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($status === 200 || $status === 204) {
    echo "Deleted successfully. Status: " . $status;
} else {
    echo "Delete failed. Status: " . $status;
}
?>

Output:

Sample response of JSONPlaceholder

Deleted successfully. Status: 200

Code explanation

  • CURLOPT_CUSTOMREQUEST sets the HTTP method to DELETE.
  • The request has no body, only the URL with the id.
  • A real API answers 200 OK or 204 No Content when the delete works, and 404 when the record does not exist. JSONPlaceholder gives 200 and an empty JSON {}.

JSONPlaceholder does not really delete anything. If you read the same post again with a GET request, it is still there. A real API would give 404.


Be careful with DELETE

  • A delete can not be undone. Ask the user for a confirmation before you send it.
  • Send the request only for the logged-in users who have the right to delete.
  • Check the status code, and never say “deleted” if the API gave an error.

What you learned in this tutorial

Now you can connect your PHP website with many services. To expose your own data as an API, read about Composer and frameworks, or use forms and MySQL to build it.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.