Example API Call in PHP

It is often more convenient to use a library in order to simplify HTTP requests to an external API. For the purposes of this example, we will use a very simple PHP class, which is a wrapper around the cURL library. See below the example for the Request class.

We can make an API request like so:

//Make the HTTP request
$response = Request::get('https://services.trade-traks.ca/api/Expense/get',[
	'token' 	=> '68b64c293ad80e3b40d73afc938b4d4080cc627a2505e495a653d3084bb6',
	'limit' 	=> 5,
	//note request parameter that hold arrays must be a JSON string
	'filters'	=> json_encode([
		['cost >',60]
	])
]);

The API response will be a JSON string.

Using the following Request class:

/**
* Wrapper Class for sending cURL requests
*/

class Request {

	/**
	* @param $options = [
	*	'type' => string, get/post,
	*	'fields' => [], //associative array
	* ]
	*/
	public static function http_request($url, $options) {
		

		if (isset($options['type']) && strtolower($options['type']) == "post") {
			$type = 1;

			$curl = curl_init($url);

			curl_setopt($curl,CURLOPT_POST,1);

			if (isset($options['fields']))
				curl_setopt($curl,CURLOPT_POSTFIELDS,$options['fields']);
		}
		elseif (isset($options['fields']) && count($options['fields']) > 0) {
			$query_params = http_build_query($options['fields']);

			$url .= "?".$query_params;

			$curl = curl_init($url);
		}
		else 
			$curl = curl_init($url);

		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_FOLLOWLOCATION => true,
		    CURLOPT_HTTPHEADER => $headers
		));

		$response = curl_exec($curl);

		curl_close($curl);

		return $response;
	}

	//shorthand function
	public static function get($url, $fields = [])
	{
		return self::http_request($url,[
			'type' => 'get',
			'headers' => $headers,
			'fields' => $fields
		]);
	}

	public static function post($url, $fields = [])
	{
		return self::http_request($url,[
			'type' => 'post',
			'headers' => $headers,
			'fields' => $fields
		]);
	}
}