2

I am using an external api where i have been given the following details related to that api

API KEY (Mandatory Header) :- apikey : "xxxxx"
Stage Server Base Url :- https://example.com
To add Details API :- POST(/student/{student_id})

What I plan to do is:

I would be collecting data from users through codeigniter form and then will forward the data to the above api and get a response from the api and accordingly if its a success then would perform furthur actions or else need to display error message

However for testing purpose i am using a static array and trying to send it to the api.

What actually is happening is I am getting a blank result and so not sure if it is working or not.

Following is my code

<?php
$apiKey = 'xxxx';
$url = 'https://www.example.com';
$data = array("name"=> "ABC","location"=> "loc","class"=> 'tenth',"area"=> "area");

$ch = curl_init( $url );
$payload = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
$headers= curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: ' . $apiKey));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
echo "<pre>$result</pre>";

?>

PS:I am new to api and curl so a little explanation along with the solution would be appreciated

Sam
  • 1,381
  • 4
  • 30
  • 70

2 Answers2

1
$ch = curl_init('http://www.example.com');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Accept: application/json',                                                                                
    'Authorization:Basic '.$apikey,
    )                                                                       
);                                                                                                                  
$result = json_decode(curl_exec($ch));

try to add whether its Basic or Bearer in authorization header. Hope it works for you.

Ramkumar P
  • 196
  • 3
  • 13
-1

you should use like below statement

curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
Arun Kumar
  • 35
  • 6