You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE;
$ERROR_MESSAGE = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din't work well for me. I found out the curl
method to be faster and more reliable.