Introduction

This is the documentation for the PHP client for Objectia® API. You can find the source code for the client on GitHub. We have API clients in several other programming languages hosted on GitHub.

Requirements

The PHP client for Objectia API requires PHP version 7.1 or later. If you’re using a Mac or Linux machine, you probably already have PHP installed. You can check this by opening up a terminal and running the following command:

php --version

If it is not installed, follow the PHP installation instructions.

If you're using a Windows machine, please follow the official PHP tutorial to install PHP.

IMPORTANT

While many versions of PHP will work for this quickstart, please pay attention to supported PHP releases. Always update unsupported versions when doing web development, as older versions will not receive security updates.

Installation

The easiest way to install objectia-php is using Composer. Composer is the de facto standard package manager for PHP web development. If you haven't yet installed it, here are the installation instructions for your platform:

composer require objectia/client

Alternatively, you can create a file named composer.json. In that file, add:

{
    "require": {
        "objectia/client": "^1.0"
    }
}

Then run

composer install

And composer will install the latest 1.x version of the PHP client for Objectia API.

Using

Now that we have PHP and objectia-php installed, we can start using the API. In the example below we will look up the geolocation of the IP address 8.8.8.8.

<?php
use Objectia\Client;

$apiKey = $_ENV["OBJECTIA_APIKEY"]

$client = new Client($apiKey);
$location = $client->geoip->get("8.8.8.8");

echo "Country code: " . $location["country_code"];

TIP

If you do not have an API Key, you can easily generate one by heading over to the API settings page.

Error handling

The API client will throw an APIException upon error, and you handle the errors in the normal way with a try-catch statement. APIException has three subclasses: APIConnectionException, APITimeoutException and ResponseException.

If you enter an invalid IP address, you will get an exception:

<?php
use Objectia\Client;
use Objectia\Exceptions\ResponseException;

$apiKey = $_ENV["OBJECTIA_APIKEY"]

$client = new Client($apiKey);

try {
    $location = $this->client->geolocation->get("x");
} catch (ResponseException $e) {
    echo "API request failed:";
    echo "* Status: " . $e->getStatus();
    echo "* Code: " . $e->getErrorCode();
    echo "* Message: " . $e->getMessage();
}

The example above will print the following:

API request failed:
* Status: 400
* Code: err-invalid-ip
* Message: Invalid IP address

You should use the getErrorCode() method to determine the reason for the error. Please observe that this is not the same method as Exception::getCode().

You will find all the error codes in the REST API documentation.