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

The HTTP PUT method is used to update an existing record. You send the id of the record in the URL, and the new data in the request body. If you are new to cURL, read GET data using cURL first.


Update data with PUT

We update the post with id 1. The endpoint is https://jsonplaceholder.typicode.com/posts/1. cURL has no special option for PUT, so we set the method with CURLOPT_CUSTOMREQUEST.

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

$data = [
    "id"     => 1,
    "title"  => "Updated title",
    "body"   => "Updated body text",
    "userId" => 1
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
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);
$result = json_decode($response, true);

echo "Status: " . $status . "<br>";
echo $result["id"] . " - " . $result["title"];
?>

Output:

Sample response of JSONPlaceholder

Status: 200
1 – Updated title

Code explanation

  • The id of the record goes in the URL (/posts/1).
  • CURLOPT_CUSTOMREQUEST sets the method to PUT, and the data is sent in CURLOPT_POSTFIELDS.
  • The API answers with the updated record and status 200. Some APIs answer with 204 and no content.

PUT or PATCH?

PUTPATCH
Sends the complete record, and replaces itSends only the fields that you want to change
Fields that you forget can be removed or resetOther fields stay as they are

To use PATCH, write "PATCH" in CURLOPT_CUSTOMREQUEST, and send only the changed fields. Check the documentation of the API to know which one it supports.

Next chapter: DELETE data using cURL.


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