PHPackages                             fm5z/apidae-api-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. fm5z/apidae-api-php

ActiveLibrary[API Development](/categories/api)

fm5z/apidae-api-php
===================

Apidae API official PHP Client

1.0.x-dev(5y ago)0391MITPHPCI failing

Since Aug 2Pushed 1y agoCompare

[ Source](https://github.com/fm5z/apidae-api-php)[ Packagist](https://packagist.org/packages/fm5z/apidae-api-php)[ RSS](/packages/fm5z-apidae-api-php/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (2)Versions (4)Used By (0)

Apidae PHP Api Client
=====================

[](#apidae-php-api-client)

PHP Client for Rhône Alpes Tourisme [Apidae API](http://blog.apidae-tourisme.com/)

- All API methods exposed with input validation;
- Authentication set automatically (for both credentials and OAuth end points);
- Apidae SSO helpers;
- Error handling;
- Handle exports (Zip download and reading);
- Based on Guzzle 6.

This documentation only handle the PHP implementation, for further questions please refer to [Apidae API Documentation](https://dev.apidae-tourisme.com/).

Install
-------

[](#install)

### Via Composer

[](#via-composer)

```
composer require fm5z/apidae-api-php

```

### Standalone (when you can't use Composer)

[](#standalone-when-you-cant-use-composer)

If you can't use Composer, you can download a full archive [here](https://dev.apidae-tourisme.com/wp-content/uploads/2019/02/sitra-api-php-1-0-5.zip)

- Extract the ZIP file and add the whole "vendor" directory to your project;
- Include the file `vendor/autoload.php` if you do not have an autoloader already.

However we **strongly** encourage you to [use Composer](https://getcomposer.org/) on all your projects.

Usage
-----

[](#usage)

### Creating a Client

[](#creating-a-client)

You need to create a `Client` instance:

```
$client = new \Apidae\ApiClient\Client([
    'apiKey'           => 'XXX',
    'projectId'        => 672,
    'baseUrl'          => 'https://api.apidae-tourisme.com/',
    'OAuthClientId'    => 'XXX',
    'OAuthSecret'      => 'XXX',
    'exportDir'        => '/tmp/apidaeExports',

    // Http client configuration
    'timeout'          => 0,
    'connectTimeout'   => 0,
    'proxy'            => null,
    'verify'           => true,

    // Global settings for touristic objects queries
    'responseFields'   => [],
    'locales'          => ['fr', 'en'],
    'count'            => 20,

    // For SSO
    'ssoBaseUrl'       => 'http://base.fm5z.com',
    'ssoRedirectUrl'   => 'http://localhost/',
    'ssoClientId'      => 'XXX',
    'ssoSecret'        => 'XXX',
]);

// You can also only use the mandatory parameters (all options have sensible defaults).
$client = new \Apidae\ApiClient\Client([
    'apiKey'           => 'XXX',
    'projectId'        => 672,
]);
```

This class is stateless and can be used as a service. You can then call any method directly:

```
$metadata = $client->getMetadata(['referenceId' => 123457, 'nodeId' => 'jolicode']);
$search = $client->searchDetailedAgenda(['query' => '{"searchQuery": "vélo"}']);
$search = $client->searchObject(['query' => '{"searchQuery": "vélo"}']);
$object = $client->getObjectById(['id' => 163512]);
```

Result is always a decoded PHP Array.

#### Options

[](#options)

- `apiKey`: Project API Key;
- `projectId`: Corresponding projectId;
- `baseUrl`: Not mandatory, useful if you want to hit pre-production i.e.;
- `OAuthClientId`: Only for Metadata, a valid OAuth Client Id;
- `OAuthSecret`: Only for Metadata, the corresponding secret;
- `exportDir`: The directory where we store and extract ZIP exports;
- `timeout`: Float describing the timeout of the request in seconds;
- `connectTimeout`: Float describing the number of seconds to wait while trying to connect to the server;
- `proxy`: [String or array to specify](http://guzzle.readthedocs.org/en/latest/clients.html#proxy) an HTTP proxy (like `http://username:password@192.168.16.1:42`);
- `verify`: [Boolean or string to describe](http://guzzle.readthedocs.org/en/latest/request-options.html#verify) the SSL certificate verification behavior of a request;
- `responseFields`: Allow to filter the fields returned globally for all object related queries ([documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/filtrage-des-donnees));
- `locales`: Allow to filter the locales returned globally for all object related queries ([documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/filtrage-des-langues));
- `count`: Allow to change the number of results globally for all object related queries;
- `ssoBaseUrl`: Base URL for SSO authentication ([documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/oauth/single-sign-on));
- `ssoRedirectUrl`: The URL where SSO user will be sent back in your application;
- `ssoClientId`: The SSO OAuth client ID;
- `ssoSecret`: The SSO OAuth client secret.

#### Handling errors

[](#handling-errors)

We recommend that all API calls are done in a try block.

##### API Errors

[](#api-errors)

Errors from the API are wrapped in `Apidae\ApiClient\Exception\ApidaeException`.

```
try {
    $cities = $client->getReferenceCity(['query' => '{"codesInsee": ["38534", "69388", "74140"]}']);
} catch (\Apidae\ApiClient\Exception\ApidaeException $e) {
    echo $e->getMessage();
}
```

The Exception message is **not** for public display as it may contains credentials.

##### Validation Errors

[](#validation-errors)

Validations errors happens before the query and assume you did not respect the defined schema for a method.

They are represent by `GuzzleHttp\Command\Exception\CommandException`.

##### Metadata Errors

[](#metadata-errors)

The JSON used for metadata editing is complex and come with his own Exception `Apidae\ApiClient\Exception\InvalidMetadataFormatException`.

API methods
-----------

[](#api-methods)

### Read Touristic Objects

[](#read-touristic-objects)

#### Get by Id

[](#get-by-id)

[Full documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/liste-des-services/v002objet-touristiqueget-by-id)

```
$object = $client->getObjectById(['id' => 163512]);
```

#### Get by Identifier

[](#get-by-identifier)

[Full documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/liste-des-services/v002objet-touristiqueget-by-identifier)

```
$object = $client->getObjectByIdentifier(['identifier' => 'sitraSKI275809']);
```

### Search Touristic Objects

[](#search-touristic-objects)

- [Full request documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/format-des-recherches)
- [Response format documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/formats-de-reponse)

Search queries accept a JSON formatted search object that must contain your API credentials, by using this client, you can send only the search related fields in your JSON and we will add automatically the appropriate fields if absent.

#### List search results

[](#list-search-results)

You can send search in a couple of ways:

```
// As JSON string
$search = $client->searchObject(['query' => '{"searchQuery": "vélo"}']);

// As PHP Array
$search = $client->searchObject(['query' => [
    "searchQuery" => "vélo",
    "count" => 20,
    "first" => 10,
]]);

// With the credentials it works too (but we handle them for you)
$search = $client->searchObject(['query' => [
    "searchQuery" => "vélo"
    "apiKey" => 'XXX',
    "projetId" => 1,
]]);
```

#### Search with identifier

[](#search-with-identifier)

When you only need the object ids:

```
$client->searchObjectIdentifier(['query' => '{"searchQuery": "vélo"}']);
```

### Agenda

[](#agenda)

Like normal search, you do not need to provide the API credentials to use those methods.

- [Full request documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/format-des-recherches)
- [Response format documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/formats-de-reponse)

#### List search agenda results

[](#list-search-agenda-results)

```
$client->searchAgenda(['query' => '{"searchQuery": "vélo"}']);

$client->searchAgenda(['query' => '{"searchQuery": "vélo", "count": 88, "responseFields": ["nom"]}']);
```

#### Search agenda with identifier

[](#search-agenda-with-identifier)

```
$client->searchAgendaIdentifier(['query' => '{"searchQuery": "vélo"}']);
```

#### List search agenda results with detailed view

[](#list-search-agenda-results-with-detailed-view)

```
$client->searchDetailedAgenda(['query' => '{"searchQuery": "vélo"}']);
```

#### Search agenda with identifier with detailed view

[](#search-agenda-with-identifier-with-detailed-view)

```
$client->searchDetailedAgendaIdentifier(['query' => '{"searchQuery": "vélo"}']);
```

### Metadata

[](#metadata)

[Full documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/metadonnees)

#### List metadata

[](#list-metadata)

You can ask for metadata like this:

```
// Only with the mandatory fields
$metadata = $client->getMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode'
]);

// More detailed search
$metadata = $client->getMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode',
    'targetType' => 'membre'
]);

$metadata = $client->getMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode',
    'targetType' => 'membre',
    'targetId' => 21
]);
```

#### Delete metadata

[](#delete-metadata)

In the same way, you can delete metadata:

```
$client->deleteMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode',
    'targetType' => 'membre',
    'targetId' => 21
]);

// Remove them all
$client->deleteMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode'
]);
```

#### Insert and update metadata

[](#insert-and-update-metadata)

Metadata API accept a large number of formats, they are all supported by this client.

```
// Simple way on "general" target
$client->putMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode',
    'metadata' => [
        'general' => '{"MyInfos": "Nice weather"}',
    ]
]);

// Simple, with a targetId of 21 on "membres" target
$client->putMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode',
    'metadata' => [
        'membres.membre_21' => '{"MyInfos": "Nice weather"}',
    ]
]);

// Multiple (notice the double JSON encoding)
$client->putMetadata([
    'referenceId' => 123457,
    'nodeId' => 'jolicode',
    'metadata' => [
        'node' => json_encode([
            'general' => json_encode(['toto' => true, 'foo' => 'bar']),
            'membres' => ([
                ['targetId' => 111, 'jsonData' => json_encode(['foo' => 'barbar'])]
            ]),
        ])
    ]
]);
```

### Reference

[](#reference)

Like normal search, you do not need to provide the API credentials to use those methods.

[Full documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/api-de-diffusion/liste-des-services#referentiel)

#### Cities

[](#cities)

```
$cities = $client->getReferenceCity([
    'query' => '{"codesInsee": ["38534", "69388", "74140"]}'
]);
```

#### Elements

[](#elements)

```
$elements = $client->getReferenceElement([
    'query' => '{"elementReferenceIds": [2, 118, 2338]}'
]);
```

#### Internal Criteria

[](#internal-criteria)

```
$criteria = $client->getReferenceInternalCriteria([
    'query' => '{"critereInterneIds":[1068, 2168]}'
]);
```

#### Selections

[](#selections)

```
$selections = $client->getReferenceSelection([
    'query' => '{"selectionIds":[64, 5896]}'
]);
```

### Exports

[](#exports)

[Full documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/exports)

*This feature require the PHP Zip extension and write permission on the filesystem.*

Exports are an asynchronous feature of Apidae allowing you to retrieve a large quantity of data without performing a lot of API calls. When a new export is done via Apidae and ready to take care, your application receive a notification which looks like this:

```
$exportNotification = $_POST;

// What Apidae sends:
array(
    "statut" => "SUCCESS",
    "reinitialisation" => "false",
    "projetId" => "672",
    "urlConfirmation" => "https://api.apidae-tourisme.com/api/v002/export/confirmation?hash=XXX",
    "ponctuel" => "true",
    "urlRecuperation" => "http://export.fm5z.com/exports/XXX.zip",
);
```

You **must** store those information and answer Apidae as soon as possible with a success response.

Then, to handle this export, you need to:

1. download the export in a memory efficient way;
2. extract the files locally;
3. do your own logic about what you need;
4. and if everything is OK, you must call "urlConfirmation".

The library handle the first two points and the last one for you!

#### Download and extract export

[](#download-and-extract-export)

Simply call the `getExportFiles` method and provide the `urlRecuperation`:

```
$exportFiles = $client->getExportFiles([
    'url' => $exportNotification['urlRecuperation']
]);
```

`$exportFiles` is then a [`Finder`](http://symfony.com/doc/current/components/finder.html) object you can iterate on:

```
// Get all the files and display their content
foreach ($exportFiles->files() as $file) {
    echo $file->getRealpath();
    echo '';
    echo $file->getContents();
    echo '';
}

// Filter files by name...
foreach ($exportFiles->name('objets_lies_modifies-14*') as $file) {
    echo $file->getRealpath();
}

// Decode file contents (XML or JSON, see your Apidae settings)
foreach ($exportFiles->files() as $file) {
    // $xml = simplexml_load_string($file->getContents());
    // print_r($xml);

    $json = \GuzzleHttp\Utils::jsonDecode($file->getContents(), true);
    print_r($json);
}
```

#### Confirmation

[](#confirmation)

When you have finished your tasks, you must confirm to Apidae that everything went fine.

```
// With the export hash
$client->confirmExport(['hash' => 'XXX']);

// Or, with the full URL given in the notification
$client->confirmExport(['hash' => $exportNotification['urlConfirmation']]);
```

#### Cleaning up files

[](#cleaning-up-files)

All the files are downloaded and extracted in the `exportDir` directory (see options).

We provide a method to clean this directory after you have done your business logic with the files:

```
$client->cleanExportFiles();
```

### Using the SSO

[](#using-the-sso)

[Full documentation](https://dev.apidae-tourisme.com/fr/documentation-technique/v2/oauth)

You must configure your client with the SSO options ('ssoRedirectUrl', 'ssoClientId' and 'ssoSecret' at least), then forward your user to the Apidae authorization URL. The user can then give your application the permission to access his data and will be redirected on your application with a code. This code is used to get an Access Token.

```
$client = new \Apidae\ApiClient\Client([
    'ssoRedirectUrl' => 'http://example.com/TODO',
    'ssoClientId'    => 'XXX',
    'ssoSecret'      => 'XXX',
]);
