Calling REST via PHP

Hello,

The REST API documetation is a bit lite on the PHP examples. So, I thought it might useful to start a thread where we can compile a few examples to help others out and hopefully save some time. Below are two examples making call to the REST API via PHP. Both are tested and work fine. Both examples are calling the method, CRM/Constituents/{constituentId}. Please, make sure to update the login, password, and URL if you choose to try it. I will post a ready to go version in my files so you can download it. When I get some more time I will add some examples using "PUT" and  some local procedure to populate/update a local table. Hope it helps.

Travis

Example 1 cURL:

$login = 'YourUserName:UserGroup:MachineName';
$password = 'TessituraPassword';
$url = 'https://SomeDomain.tessituranetworkramp.com/TestAPI/TessituraService/CRM/Constituents/{constituentId}'; // replace {constituentId} = a consituent number, example 70865
$method = 'GET';  
$data = false;

/*******************************************************************************
cURL function

http://php.net/manual/en/book.curl.php
********************************************************************************/
function CallRESTapi($method,$url,$login,$password,$data)

{
    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }
    
    
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_USERPWD,"$login:$password");
    curl_setopt($curl, CURLOPT_HTTPGET, 1);

    $results = curl_exec($curl);

    curl_close($curl);
    
    return $results;

}

//call the function
$fnc_data= CallRESTapi($method,$url,$login,$password,$data);
echo $fnc_data;

 

Example 2 file_get_contents:

/*******************************************************************************
file_get_contents

http://php.net/manual/en/function.file-get-contents.php
********************************************************************************/

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$login:$password")
    )
));
$data = file_get_contents($url, false, $context);

echo $data;



[edited by: Travis Armbuster at 2:29 PM (GMT -6) on 2 May 2017]
Parents
  • Former Member
    Former Member $organization

    Hi,

    I was trying out the cURL example to get a new SeesionKey. The following are the only changes I made to the code along with my credentials. But it is not still working. Can someone help with that?

    $url = 'https://{our_service_address}/Web/Session';
    $method = 'POST';
    $data = "{IpAddress: ''}";

    What other settings do I have to pass? Ultimately, I will use the new SessionKey to LoginAsGuest. I appreciate any additional hint on that.

  • Have you confirmed that you can run the operation using either a REST client like Postman or the built-in REST Client?

Reply Children
  • Former Member
    Former Member $organization in reply to Gawain Lavers

    Thanks Gawain for responding.

    Yes, both worked fine for me. For the $data part, I am not really sure if that is equivalent with the request body part which requires only the IpAddress. I was not sure how to pass it to cURL.

    The returned object was:

    {"Message":"An error has occurred."}

  • You need ip and businessUnit at a min if I remember correctly.

     {
      "IpAddress": "",
      "BusinessUnit": 2
    }

  • Former Member
    Former Member $organization in reply to Travis Armbuster

    I just tried this

    $data = array("'IpAddress' : ''", "'BusinessUnit': 2");

    but it didn't work. The buit-in REST Client returns a SessionKey without the 'BusinessUnit. It needs only 'IpAddress'. Same with Postman.

  • I will get this in a function later.

    $login = 'unsername:group:location';
    $password = 'password';
    $url = 'domain.tessituranetworkramp.com/.../New';
    $data =  array('IpAddress'=> '17.16.1.1');
    
      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_USERPWD,"$login:$password");
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, 1); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($ch, CURLOPT_POSTFIELDS,  http_build_query($data)); 
    
    
       $result = curl_exec($ch);
       if(curl_errno($ch) !== 0) { error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch)); } 
       curl_close($ch);
       print_r($result); 
    
  • Former Member
    Former Member $organization in reply to Travis Armbuster

    Thanks Travis. I got it working now. These were the changes I made.

    1) For POST method http_build_query is not required. I believe it is for GET.

    2) I didn't need to pass any ip address. I used empty string. And It doesn't have to be an array.

    3) The timeouts were not significant for this call. So, I didn't use those lines.

    Thanks again. I appreciate.

  • The ip was simply a place holder and yes timeouts are not needed, but if you got it to work without using http_build_query, then post up your approach (to help others). To expand on this for others... Http_build_query is not specific to get or post. It simply builds the query string format (and easier to understand). For the array in the example above, http_build_query would output  IpAddress=17.16.1.1

    If you really do not want to use http_build_query, then loop through the array and build the post args, which is what I use (example below).

    $data =  array('IpAddress'=> '17.16.1.1');
    
    //Build postfield string from data array
    	$params = '';
    	foreach($data as $key=>$value){
    		$params .= $key.'='.$value.'&';
    	}
    	$params = trim($params, '&');

    ...

      curl_setopt($ch, CURLOPT_POSTFIELDS,$params);

    Also, I will finish the original example soon. That will allow for GET, POST, PUT in one function. It was my intention to continue building on this thread, but a website redesign project got in my way and I kind of left it die. But your post gave me a renewed sense of purpose.

    Travis

  • Former Member
    Former Member $organization in reply to Travis Armbuster

    This is what worked for me. I am returning the error number if there is one, or the $result returned on success. I am not doing delete that is why I returned false in the switch statement.

    function CallRESTapi($method, $url, $login, $password, $data)
    {
    $curl = curl_init($url);

    switch ($method) {
    case "POST":
    curl_setopt($curl, CURLOPT_POST, 1);
    if ($data)
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    break;
    case "PUT":
    curl_setopt($curl, CURLOPT_PUT, 1);
    break;
    case "GET":
    curl_setopt($curl, CURLOPT_HTTPGET, 1);
    if ($data)
    $url = sprintf("%s?%s", $url, http_build_query($data));
    break;
    default:
    return false;
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_USERPWD, "$login:$password");

    $results = curl_exec($curl);
    curl_close($curl);

    // return either the error no if failed, or the $results;;
    return curl_errno($curl) ? curl_errno($curl) : $results;
    ;
    }