PHP : REST API – DELETE data using cURL
In this tutorial, we will learn how to DELETE some REST API data using cURL functions in PHP.
If you are not familiar with basic cURL process and functions, read the previous tutorial: PHP: REST API – GET data using cURL
SAMPLE REST API to DELETE data using cURL
We will use Dummy REST API Example website to work with HTTP DELETE method using cURL.
API URL to DELETE an employee: https://dummy.restapiexample.com/api/v1/delete/17
In this API URL (also called route or endpoint), you will use the particular employee id to delete his records.
Note: The DELETE API URL is actually incorrect in the given (example) website. Please use ‘/delete/’ instead of ‘/update/’ as mentioned above.
PHP program to DELETE REST API data using cURL
In the following PHP program, we will delete an employee with id ‘19465’. If a user exists, it will be deleted and a successful response will be received. You need to make sure to pass an employee id that actually exists.
<?php // User data to send using HTTP POST method in curl $data = array(); // Data should be passed as json format $data_json = json_encode($data); // API URL to send data $url = 'https://dummy.restapiexample.com/api/v1/delete/2'; // curl intitite $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $url); // Set json header to received json response properly curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json))); // SET Method as a DELETE curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "DELETE"); // Pass user data in POST command curl_setopt($curl_handle, CURLOPT_POSTFIELDS,$data_json); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); // Execute curl and assign returned data into $response = curl_exec($curl_handle); // Close curl curl_close($curl_handle); // See response if data is posted successfully or any error print_r ($response); ?>
First, we have initiated a cURL session. After that, we sent HTTP DELETE command to REST API DELETE URL. Suppose you want to delete an employee having id ‘19465’. Then, the API URL will be ‘http://dummy.restapiexample.com/api/v1/delete/19465’. If the given employee found, it will be deleted. You will receive some successful response as well.
If you want to verify data after deletion, you can get employee data on the following URL.
API URL to GET Employees data: https://dummy.restapiexample.com/api/v1/employees
We have covered simple REST API methods using PHP cURL functions to interact with API data. There are few other methods also available. You can search for more online dummy REST APIs and practise more.
|Exercises & Assignments|
|No Content Found.|
|Interview Questions & Answers|
|No Content Found.|