Cara Panggil REST API di Client Menggunakan PHP dan cURL

POST

$url = "url yang jadi interface";    
$content = json_encode("data body yang di post dalam bentuk php array");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

curl_close($curl);

$response = json_decode($json_response, true);

GET

$url = "url yang jadi interface";    

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_HTTPGET, 1)

$json_response = curl_exec($curl);

curl_close($curl);

$response = json_decode($json_response, true);

untuk menambahkan authentikasi pada saat memanggil API menggunakan bearer atau token authentication, bisa ditambahkan di dalam komponen array sejajar dengan “Content-type”

misalnya seperti

$url = "url yang jadi interface";    

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", "authorization: Bearer <token>"));
curl_setopt($curl, CURLOPT_HTTPGET, 1)

$json_response = curl_exec($curl);

curl_close($curl);

$response = json_decode($json_response, true);

 

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.