PHP : REST API – POST data using cURL

An HTTP POST request is used to create new data, like a new user or a new post. In this chapter we send JSON data to an API with cURL. If you are new to cURL, read GET data using cURL first.


Send data with POST

We create a new post using the endpoint https://jsonplaceholder.typicode.com/posts. We send the data as JSON, so we also set the Content-Type header.

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

$data = [
    "title"  => "Learn PHP",
    "body"   => "REST API using cURL",
    "userId" => 1
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, true);
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 "New post id: " . $result["id"];
?>

Output:

Sample response of JSONPlaceholder

Status: 201
New post id: 101

Code explanation

  • json_encode($data) converts the PHP array to JSON text.
  • CURLOPT_POST sets the method to POST, and CURLOPT_POSTFIELDS is the data to send.
  • The Content-Type: application/json header tells the API that we send JSON.
  • Status 201 Created means that the new record was created. The API gives the new id in the response.

JSONPlaceholder only pretends to save the data. It always gives id 101 for the new post, but the post is not stored, so you will not see it later. A real API will save it.


Send a form style POST

Some APIs do not want JSON. They want normal form data. In that case pass an array to CURLOPT_POSTFIELDS, or use http_build_query($data), and do not send the JSON header.

Note: When you send private data, always use an https:// URL. If the API needs a token, add it in the header: "Authorization: Bearer YOUR_TOKEN".

Next chapter: PUT (Update) data using cURL.


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