REST API (POST/GET/PUT/DELETE) in php

REST API (POST/GET/PUT/DELETE) in php

Create a POST Request

$postdata = array('name'=>'Hosting Transfer','price'=> '250');
$data_json = json_encode($postdata);


$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234") ,
    'Content-Length: ' . strlen($data_json)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

echo '
'; print_r($response);*

Create a PUT request

$postdata = array('name'=>'Wpengine Hosting Transfer','price'=> '250');

$data_json = json_encode($postdata); 

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234") ,
    'Content-Length: ' . strlen($data_json)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product/2');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

echo '
'; print_r($response);

Create a DELETE request

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234")
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product/4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

echo '
'; print_r($response);

Create a GET request

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234") 
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

echo '
'; print_r(json_decode($output));

Leave a Reply

Your email address will not be published. Required fields are marked *