PHP : REST API – POST data using cURL
In this tutorial, we will learn how to POST API data using cURL functions. An HTTP POST is often used to create new content.
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 POST Method
We will use Dummy REST API Example website to work with HTTP POST method and create a new employee record.
API URL to create a new Employee: https://dummy.restapiexample.com/api/v1/create
To create a new employee, we need to POST data in following JSON format. We will use cURL to send this data.[{"id":"110","employee_name":"Deepak Kumar","employee_salary":"74000","employee_age":"42"}]
PHP program to POST REST API data using cURL
In the following PHP program, we will send new user details in given JSON format. This data will be passed to the given URL using HTTP POST method in cURL and create a new user.
<?php
// User data to send using HTTP POST method in curl
$data = array('name'=>'New User 123','salary'=>'65000', 'age' => '33');
// Data should be passed as json format
$data_json = json_encode($data);
// API URL to send data
$url = 'https://dummy.restapiexample.com/api/v1/employees';
// curl initiate
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// SET Method as a POST
curl_setopt($ch, CURLOPT_POST, 1);
// 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
curl_close($ch);
// See response if data is posted successfully or any error
print_r ($response);
?>
Code Explanation
First, we have prepared data for a new user in JSON format. Then we passed those user data to given API URL via HTTP POST Method. After that, we executed CURL & stored received data. This will create a new user with data send as JSON.
If a similar user name exists in the API, it will throw an error for duplicate records. Therefore, change user data in JSON and try again.
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: http://dummy.restapiexample.com/api/v1/employees
In the next chapters, we will use cURL methods to perform an update and delete operations using API data.
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |