# DeviceAtlas Device API Usage #
This document describes the DeviceAtlas API and how it is used.
The DeviceAtlas Device Identification API consists of two libraries. A core
library containing all the main identification logic and a secondary
extension library to allow for easier integration into a web application
context.
## Data File ##
The DeviceAtlas API relies on a device data file to function. DeviceAtlas
provides daily data file updates. The DeviceAtlas API has the capability to
automatically download and load the latest data file on a scheduled basis.
Please note that basic telemetry data such as the number of API lookups
are collected when using the download and load functionality.
If however your integration cannot make use of the automatic download and load
feature it is recommended to download the data file on a regular basis. This can
be done manually from your account page or automated via the https://deviceatlas.com/getJSON page.
Please see the [Data File Configuration documentation](README.DataFile.html) and
the [Device Data guide](https://deviceatlas.com/resources/getting-the-data/device-data)
for more information.
### Loading the data file ###
The DeviceAtlas API provides multiple methods to load the data file.
#### Downloading and loading the data file ####
The following examples download the data file, save it to the file system,
load it into the DeviceAtlas API and schedule a background task to download and load
a fresh data file at a configured time in the future.
Please see the [Data File Configuration documentation](README.DataFile.html)
to obtain the data file download URL and for data file configuration options.
_Example: using default configuration_
```php
use DeviceAtlas\Device\DeviceApi;
$deviceApi = DeviceApi();
$deviceApi->downloadAndLoadDataFile();
```
_Example: using custom configuration_
```php
use DeviceAtlas\Device\DeviceApi;
use DeviceAtlas\DataFile;
$dataFileUrl = ;
$downloadDir = ;
$deviceApi = DeviceApi();
$dataFile = DataFile::Builder($dataFileUrl)->fileDirectory($downloadDir)->buildDeviceDataFile();
$deviceApi->downloadAndLoadDataFileFromUrl($dataFile);
```
#### Loading an existing data file ####
The following example shows how to load a data file that is already on the filesystem.
```php
use DeviceAtlas\Device\DeviceApi;
$deviceApi = DeviceApi();
$deviceApi->loadDataFromFile();
```
The exception DataLoadingException is thrown by the above methods in case the data file cannot be loaded.
## Client Side Library - Apple Device Identification ##
In addition to the server-side API, an optional client-side Javascript library
is available. This library is important for two reasons:
1. It facilitates identification of Apple devices. Apple devices are _not_
identifiable using only HTTP User-Agent data.
2. It allows for the collection of dynamic or changing properties.
When the client-side library is embedded in a web page it collects additional
properties from the client's web browser. This data is then sent back to the
server and must be passed to the DeviceAtlas API along with the HTTP headers.
The combination of the client data and the server side data allow for accurate
identification of Apple devices.
The client-side library may be included on a webpage by adding the following
snippet:
```html
```
By default, the client-side library returns the data via a cookie. If this is
present in the `HttpServletRequest` object it will be automatically used. The
cookie name is configurable via the `Config` class.
Alternatively, the client data may be returned via AJAX and passed to the server
side API manually.
For additional information, please see the [Client Side Library](https://docs.deviceatlas.com/apis/clientside/latest/README.ClientSide.html) documentation.
## Setup & Usage ##
The usage of the DeviceAtlas server side library is straightforward. In all
cases, the data file must be loaded before any device identification calls are
made.
> **Note:** It is highly recommended to ensure the data file is only loaded once.
This is particularly important for batch processing and web applications.
### PHP Version ###
The DeviceAtlas API requires at least the PHP 7.0 (or above).
### Library ###
The DeviceAtlas Device Detection API consists of two interfaces as below:
**DeviceApi**
The main DeviceApi that loads the Device data and detects and returns the
properties for a set of request headers or the user-agent. Client-side
properties can be optionally passed to this library to get more accurate
results.
**DeviceApiWeb**
A small extension to the main API that allows automatic extraction of the
request headers and client-side properties from the request. It is preferred to
use this library for real-time device detections in web applications.
### Usage Examples ###
The following sections shows how to call the DeviceApi. Please note that
exception handling has been omitted for brevity.
#### Detection via User-Agent ####
To lookup the properties by manually passing a User-Agent string to the API:
```php
use DeviceAtlas\Device\DeviceApi;
$deviceApi = DeviceApi();
$deviceApi->downloadAndLoadDataFile();
// pass an identifier to the API
$userAgent = "Mozilla/5.0 (Linux; Android 12; SM-G998B) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/102.0.0.0 Mobile Safari/537.36";
$properties = $deviceApi->getProperties($userAgent);
// print all properties
foreach ($properties as $propertyName => $property) {
printf("%s: %s (%s)\n", $propertyName, $property->getValue(), $property->getDataType());
}
// use a property
if ($properties->containsKey("mobileDevice")) {
$mobileDevice = properties->get("mobileDevice")->asBoolean();
// do something
}
// or get the property value as a string with an internal check to verify
// if the property exists in the set, otherwise the default value is returned instead.
$browserName = $properties->getOrDefault("browserName", );
```
#### Detection via Make/Model ####
Lookup the properties by passing a Make/Model string to the API. DeviceAtlas expects the
make/model string in a specific format, this format and how to obtain the Make/Model string
can be found under the "Expected string format for DeviceAtlas lookup" section [here](https://deviceatlas.com/resources/getting-started-enterprise-for-apps).
```php
use DeviceAtlas\Device\DeviceApi;
$deviceApi = DeviceApi();
$deviceApi->downloadAndLoadDataFile();
// The Make/Model identifier may be looked up by directly passing the string
$makeModel = "samsung sm-n9005";
$properties = $deviceApi->getProperties($makeModel);
// It is also possible to add the Make/Model identifier to an array for the lookup
$identifiers = [
"make-model" => $makeModel
];
$properties = $deviceApi->getProperties($identifiers);
```
#### Detection via HTTP headers ###
**Inside a web application**
The `DeviceApiWeb` extension makes it possible to do device lookups based on the
request or a whole set of HTTP headers. This allows the API to make a more
precise detection and return properties with more accurate values. For example,
some browsers distribute the user-agent information into different headers, so
it is almost impossible to correctly detect the device properties, such as type
and model from the user-agent header itself. With this new interface, the API
is able to overcome these situations.
```php
use DeviceAtlas\Device\DeviceApiWeb;
$deviceApi = DeviceApiWeb();
$deviceApi->downloadAndLoadDataFile();
// The detection is done based on the HTTP request
$properties = $deviceApi->getProperties();
// use a property
if ($properties->containsKey("browserVersion")) {
$browserVersion = properties->get("browserVersion")->asString();
// do something
}
// or get the property value as a string with an internal check to verify
// if the property exists in the set, otherwise the default value is returned instead.
$browserName = $properties->getOrDefault("browserName", );
```
**Not in a web application**
To look up the properties by manually passing a dictionary of HTTP headers to the API.
It is recommended to pass all of the HTTP headers
provided by the client. The below example shows passing a User-Agent along with
a Client Hint header. In the example, the device properties are detected from
the User-Agent and the browser properties are detected from the Client Hint
header.
```php
use DeviceAtlas\Device\DeviceApi;
$deviceApi = DeviceApi();
$deviceApi->downloadAndLoadDataFile();
// pass a collection of HTTP headers
$headers = [
"User-Agent" => "Mozilla/5.0 (Linux; Android 12; SM-G998B) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/102.0.0.0 Mobile Safari/537.36",
"Sec-CH-UA-Full-Version-List" => "\" Not A;Brand\";v=\"99.0.0.0\", \"Chromium\";v=\"102.0.5005.125\", \"Google Chrome\";v=\"102.0.5005.25\""
];
$properties = $deviceApi->getProperties($headers);
// use a property
if ($properties->containsKey("browserVersion")) {
$browserVersion = properties->get("browserVersion")->asString();
// do something
}
// or get the property value as a string with an internal check to verify
// if the property exists in the set, otherwise the default value is returned instead.
$browserName = $properties->getOrDefault("browserName", );
```
#### Passing Client Side Data ####
The data collected by the DeviceAtlas Client-side Library is automatically
passed when an `$headers` array is used. If an `$headers` array
is not available the client-side data can be passed manually as a second
parameter to the `getProperties()` method.
```php
use DeviceAtlas\Device\DeviceApiWeb;
$deviceApi = DeviceApiWeb();
$deviceApi->downloadAndLoadDataFile();
$userAgent = "Mozilla/5.0 (Linux; Android 12; SM-G998B) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/102.0.0.0 Mobile Safari/537.36";
$clientSideData = "scsVersion:2.1|bcookieSupport:1|bcss.animations:1|bcss.columns:1|bcss.transforms:1|bcss.transitions:1|sdeviceAspectRatio:1795/1010";
$properties = $deviceApi->getProperties($userAgent, $clientSideData);
// use the properties
```
#### Configuration ####
During instantiation of the `DeviceApi` object an optional config parameter may
be passed. The example below shows the setting of a custom cookie name that the
DeviceAtlas client-side data should be found in.
```php
use DeviceAtlas\Device\DeviceApi;
use DeviceAtlas\Device\Config;
$config = new Config();
$config->setCookieName("DeviceAtlasClientSide");
$config->setMaxCacheEntries(4096);
$deviceApi = new DeviceApi($config);
```
#### Additional Examples ####
Please find more complete examples in the /Examples directory.
### Optimizations ###
When the `DeviceApi` or `DeviceApiWeb` are used in a stateless environment such as in
a Web Server, the data file has to be loaded on each request because PHP is
a stateless language. While this works, it greatly impacts performance. To
address this issue this API provides ways to optimize the memory usage and
lookup performance.
#### Data File Optimization ####
_( for a stateless environment such as in a Web Server )_
It is highly recommended to use the JSON tree optimizer. The optimizer breaks
the data file into smaller parts and caches them on the disk. The API will use
the cached data instead and will only load the data needed for a certain lookup
into the memory. Significantly decreasing the amount of memory used.
When using with automatic download and load, the API will automatically optimize,
however during reload times this could lead to slow response or high memory
on runtime environment.
This can be avoided by using the separate optimization process. Read more here
[DeviceAtlas Data File Optimizer](README.DataFileOptimizer.html)
```php
use DeviceAtlas\Device\DeviceApi;
use DeviceAtlas\Device\Config;
$config = new Config();
$config->setUseTreeOptimizer(true);
$deviceApi = new DeviceApi($config);
```
This is automatically enforced for the `DeviceApiWeb` interface.
```php
use DeviceAtlas\Device\DeviceApiWeb;
$deviceApi = DeviceApiWeb();
$deviceApi->downloadAndLoadDataFile();
```
Using the `DeviceApi` or `DeviceApiWeb` as shown above will:
* Automatically optimize the data file.
* Automatically sense a newer data file when the data file is replaced or changed
and will optimize the new data file and renew the optimization cache.
* The API will use the cached data files for optimized device lookups when they
are available.
Note: as soon as the API senses a new data file, it will perform an optimization
process on its usage. This means that, in a web application, the first request
after a data file update will experience a small lag. To eliminate this lag, it
is required to manually run the optimization process using a command line tool
which comes with the API package.
Please see the [Data File Optimizer documentation](README.DataFileOptimizer.html)
for more details.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
_ Copyright (c) DeviceAtlas Limited 2023. All Rights Reserved. _
_ https://deviceatlas.com _