davek1312 / apiintegrator
Serialise/Deserialise data from third party APIs
v0.8.1
2017-07-08 23:36 UTC
Requires
- davek1312/serialise: 0.3.*
- davek1312/variableutils: 0.*
- guzzlehttp/guzzle: ^6.2
Requires (Dev)
- phpunit/phpunit: ~4.0
README
Retrieve data from third party APIs and deserialise into PHP models.
Installation
The package is available on Packagist, you can install it using Composer.
composer require davek1312/apiintegrator
Configuration
Response Model
Build your response model class. Annotate your model using the JMS annotations. Your model should have the same properties as the API response that it receives. You response model also defines the APIs response data type.
use JMS\Serializer\Annotation\Exclude;
class YourResponseModel extends Davek1312\ApiIntegrator\Models\ApiIntegratorResponseModel {
/**
* @Type("string")
*/
private $apiProperty;
/**
* The API's response format: 'json' OR 'xml'
*
* @return string
*/
public static function getResponseDataType() {
return 'json';
}
public function getApiProperty() {
return $this->apiProperty;
}
}
If the API response contains error attributes your response model class should override the base response error accessors:
use JMS\Serializer\Annotation\Type;
class YourResponseModel extends Davek1312\ApiIntegrator\Models\ApiIntegratorResponseModel {
/**
* @Type("string")
*/
private $apiErrorMessage;
/**
* @Type("integer")
*/
private $apiErrorCode;
public function getResponseErrorMessage() {
return $this->apiErrorMessage;
}
public function getResponseErrorCode() {
return $this->apiErrorCode;
}
}
Integrator
Your integrator must extend the base integrator and define the $responseModelClass
created above:
use YourResponseModel;
class YourIntegrator extends Davek1312\ApiIntegrator\ApiIntegrator {
/**
* @var string
*/
public static $responseModelClass = YourResponseModel::class;
}
Usage
Build your request model:
/*
* $url(string): The API's url
* $connectionMethod(string): The HTTP connection method e.g. GET, POST, DELETE etc.
* $connectTimeout(double): Seconds allowed to establish a connection to the API
* $requestTimeout(double): Seconds allowed to complete request
* $additionalRequestOptions(array): An optional array of request options from http://docs.guzzlephp.org/en/latest/request-options.html
*/
$requestModel = new ApiIntegratorRequestModel($url, $connectionMethod, $connectTimeout, $requestTimeout, array $additionalRequestOptions = []);
Generate your response model using your integrator:
$integrator = new YourIntegrator($requestModel);
$responseModel = $integrator->generateNewResponseModel();
Check for errors:
if($integrator->hasErrors()) {
$errorModel = $integrator->getErrorModel();
}