APIClient Documentation by Sitebase v1.0


Created: 03.03.2011 18:27
By: Sitebase (Wim Mostmans)
Email: wim@sitebase.be

Informations about Updates and New Scripts are always announced on Twitter, Facebook and LinkedIn.

Wim Mostmans Thank you for purchasing my script. If you have any questions that are beyond the scope of this help file, please feel free to email via my user page contact form here or on Twitter. Thanks so much!


Table of Contents

  1. Description
  2. How to install
  3. Headers
  4. Request methods
  5. Return content types
  6. Data and parameters
  7. Timeout
  8. Errors
  9. Response headers
  10. SSL and Certificates
  11. Reset client after request
  12. API Framework
  13. Caching
  14. FAQ
  15. Updates and New releases
  16. Support notes
  17. Other Scripts


This is a class that you can't miss in your developer toolbox. These days almost every website or application uses API's to get or store data, and that's were this class is created for. It helps you to communicate with all types of API's. Even if you don't have CURL on your server the class will fallback to an implementation that uses "fopen" without loosing any functionality. You will still be able to choose headers, request methods, timeouts and other settings.

To show you the power of this class I've created some example scripts that talk to some of the most popular API's. Below you find a list of examples that are included:

Besides these examples I've also included some other examples to show you how to do a put request, use cookies, do a SSL request, upload files and use of basic authentication.

How to install top

The steps that you need to follow to start using this script are very easy. Just copy the script/ApiClient.php file to your project and included it in your project with the following code:

include "ApiClient.php";

headers top

In this class you can add headers to your request in two manners. The first is using a key string and a value and the second is a constant and a value.

To show you the first manner:

$Client = new ApiClient();
$Client->addHeader('CustomHeader', 'value');

So this way you can add whatever header you want to a request. But there is also a list of constant headers that are commonly used. And these can be used like so:

$Client = new ApiClient();
$Client->addHeader(ApiClient::HEADER_USER_AGENT, 'Mozilla Firefox 10');
Below you find a complete list of all header constants that can be used:
const HEADER_ACCEPT = "Accept"; // Accept: text/plain
const HEADER_ACCEPT_CHARSET = "Accept-Charset"; // Accept-Charset: utf-8
const HEADER_ACCEPT_ENCODING = "Accept-Encoding"; // Accept-Encoding: [compress | gzip | identity]
const HEADER_ACCEPT_LANGUAGE = "Accept-Language"; // Accept-Language: en-US
const HEADER_AUTHORIZATION = "Authorization"; // Basic Authorization: Basic base64(username:password)
const HEADER_CACHE_CONTROL = "Cache-Control"; // Cache-Control: no-cache
const HEADER_COOKIE = "Cookie"; // Cookie: $Version=1; Skin=new;
const HEADER_COOKIEFILE = "Cookie-File"; // Cookie file: only works with curl
const HEADER_CONTENT_LENGTH = "Content-Length"; // Content-Length: 348
const HEADER_CONTENT_TYPE = "Content-Type"; // Content-Type: application/x-www-form-urlencoded
const HEADER_DATE = "Date"; // Accept: Date: Tue, 15 Nov 1994 08:12:31 GMT
const HEADER_EXPECT = "Expect"; // Expect: 100-continue
const HEADER_FROM = "Form"; // From: user@email.com
const HEADER_HOST = "Host"; // Host: en.wikipedia.org
const HEADER_MAX_FORWARDS = "Max-Forwards"; // Max-Forwards: 10
const HEADER_PRAGMA = "Pragma"; // Pragma: no-cache
const HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization"; // Proxy-Authorization: Basic base64(username:password)
const HEADER_RANGE = "Range"; // Range: bytes=500-999
const HEADER_REFERER = "Referer"; // Referer: http://en.wikipedia.org/wiki/Main_Page
const HEADER_USER_AGENT = "User-Agent"; // User-Agent: Mozilla/5.0 (Linux; X11)
const HEADER_CUSTOMREQUEST = "Request"; // Use to do a custom request. For example to communicate with DirectAdmin API "GET /CMD_API_SHOW_USERS? HTTP/1.0"

Basic authentication

Something that is commonly used to authenticate a API request is Basic authentication. The example below shows you how to use Basic authentication:

$Client->addHeader(ApiClient::HEADER_AUTHORIZATION, 'Basic ' . base64_encode('[username]:[password]'));

More about HTTP headers

More information about HTTP headers you can use can be found on this wiki page.

Request methods top

This class supports all different request methods like GET/POST/PUT and DELETE. Se below for examples how to use these different request methods.









More examples

For more and better examples take a look at the scripts in the script/examples directory.

Return content types top

By default the ApiClient returns the content like it's received. For example this will show the raw json data from the request to twitter:

$Client = new ApiClient();
$result = $Client->request('http://search.twitter.com/search.json?q=from%3Asitebase');
echo $result;

But the request method has also a second parameter where you can set what data type is returned by the API and it will automaticly convert the data in an object. So if you take the same example as above but we tell the ApiClient that the requested data is JSON than the result variable will be an object instead of a string.

$Client = new ApiClient();
$result = $Client->request('http://search.twitter.com/search.json?q=from%3Asitebase', ApiClient::CONTENT_JSON);
print_r( $result );

Below you find a list of other content types that can automaticly be parsed.

const CONTENT_PLAIN = "plain"; // This is the default
const CONTENT_JSON = "json" // For example Twitter;
const CONTENT_XML = "xml";
const CONTENT_PHP = "php";
const CONTENT_XMLRPC = "xmlrpc" // For example WordPress;
const CONTENT_QUERYSTRING = "querystring"; // For example Direct Admin

Data and Parameters top

In the above example (Return content types) we typed our data after the twitter url but that is not a really clean way to do a request. You can better use the setParams and addParam methods. Below is how the code will look when using the param methods:

$Client = new ApiClient();
$Client->addParam('q', 'from:sitebase');
$result = $Client->request('http://search.twitter.com/search.json', ApiClient::CONTENT_JSON);

The example above is with a GET request but you can also use the param method with other request methods like POST. You can also use the setParams methods to set multiple params using an array. For example:

$Client->setParams(array('firstname' => 'Wim', 'lastname' => 'Mostmans'));

Set data

Besides the params function there is also a setData method the can be used to set a block of data to send. This is only used for POST and PUT request. For an example where this can be used you can check out the Freshbooks example.

$Client->setData('The data you want to send');

Timeout top

You can also specify how long the class must wait (in seconds) before the request fails. Also check out the timeout example that is included.

$Client->setTimeout(1); // Request must be finished within a second

Errors top

Wrap you request in a try catch block so that if the request fails or gives problems you can show your users a readable message instead of a default exception error. Below you see how this is done:

try {
	$Client = new ApiClient();
	$result = $Client->request('request url here');
} catch(Exception $e) {
	// Maybe do some logging here ...
	echo 'Requset error';

Response headers top

After doing a request you can get a list of response headers send by the server with the getResponseHeaders method.

$Client = new ApiClient();
$result = $Client->request('request url here');
$headers = $Client->getResponseHeaders();

SSL and Certification top

All of the ApiClients out on the net disable verifypeer to do SSL requesst and by default ApiClient also does this, but that's not the most secure way to do requesst to an SSL API. The best way is to check the host with a certificate file. This is pretty easy with this class. See also the SSL example I've included. The certificate I'm using is the default one that is used by Firefox. That certificate bundle can be downloaded from here.

$Client = new ApiClient();
$Client->useCertificate(str_replace('\\', '/', getcwd()) . '/cacert.pem');
$result = $Client->request('https://mysite.com/api/1.0/');

Reset settings after request top

If you added some headers to the client, did a request, but now you want to do another request with other settings and headers than you can call the reset method. This will reset all the setting in the ApiClient instance.


API Framework top

This API Client is perfect to use in combination with my API Framework script. So make sure to check it out ;).

Caching top

By default this script doesn't support caching because I wanted to keep this script lightweight and to the point. If you want to cache API requests than you can use this cacing class.

Changelog top

v1.0 (13/03/2011)
* Initial version released

FAQ top

Do I always need to set the request method?

If you use want to do a GET request you don't need to set the method because the class uses the GET method by default.

Updates and New releases top

Updates and new release of the script are free to download once you have bought this item. To download a new version you go to My Account on Codecanyon and

How to download an update
Follow these steps to download the latest release

Support notes top

Right now I'm simply getting more emails and requests for support than I can manage in a timely manner. Some times I can answer emails the same day, but often it'll take me as long as a month (or longer!) to completely empty my inbox.

Before sending a support request make sure that you have done the following things:

  1. Read the full documentation file
  2. See if your answser isn't already answered in the FAQ section of the script on Codecanyon.

To be able to help solve a problem quickly, please read the entries below. I'll do my best to assist you. I provide a full range of Support except:

  1. I don't (and can't) support the 3rd-party code (i.e. external plugins, javascripts, flash players, etc.) In such cases you shall have to contact the authors.
  2. I don't support errors provoked by the strong modification of the original packages.
  3. I do customization but this isn't included in the price of the script. To get a cost estimate for a modification you can email me on wim@sitebase.be.
  4. If you sure that your improvement ideas will be helpful to others, please don't hesitate to share it with me. Most likely that it will became a free package update.
  5. If you have a more general question relating to the script on Codecanyon, you might consider visiting the forums and asking your question in the "Item Discussion" section.

Other scripts top

I have released a lot of other cool and handy scripts, so make sure to checkout our other scripts. To get an overview you can take a look at our portfolio on Codecanyon.

Once again, thank you so much for purchasing this script. As I said at the beginning, I'd be glad to help you if you have any questions relating to this theme/script. No guarantees, but I'll do my best to assist.


Go To Table of Contents