PHP : REST API – PUT (Update) data using cURL

In this tutorial, we will learn how to use HTTP PUT to update REST API data using cURL functions.

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 data to send via PUT Method

We will use Dummy REST API Example website to work with HTTP PUT method and employee record.

API URL to create a new Employee:

To update an employee, we need to pass the id of that employee in URL with updated details in following JSON format. We will use cURL to send this data.

[{"id":"110","employee_name":"Robin S","employee_salary":"7270","employee_age":"34"}]

PHP program to UPDATE user data using PUT REST API command via cURL

In the following PHP program, we will update the user with id ’10’. This data will be passed to the given URL using HTTP POST method in cURL and create a new user.

// User data to send using HTTP PUT method in curl
$data = array('name'=>'New Robin User','salary'=>'62000', 'age' => '34');
// Data should be passed as json format
$data_json = json_encode($data);
// API URL to update data with employee id
$url = '';
// curl initiate
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
// SET Method as a PUT
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
// Pass user data in POST command
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute curl and assign returned data
$response  = curl_exec($ch);
// Close curl
// See response if data is posted successfully or any error
print_r ($response);

Code Explanation

First, we have used API URL for employees (with user-id at the end) whose details need to be updated. Then, we passed updated user data to the given API URL via HTTP POST Method. After that, we executed CURL & stored received response to see if any error.

If a similar user data exists or not user id found in the API, it will throw an error for duplicate records. Therefore, pass the user id in JSON carefully and try again.

Note: Make sure not to add ‘/’ at the end of ID or URL in this API.

After successful user creation, you can find a new user at the end of the API data. You can read employee data on the following URL.

API URL to GET Employees data:

In the next chapters, we will use cURL methods to perform an update and delete operations using API data.

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