认知 / ez-api
该软件包已被放弃,不再维护。未建议替代包。
EZ API - API服务调用起点
v1.3.0
2021-09-16 16:38 UTC
Requires
- php: ^8.0
- guzzlehttp/guzzle: ^7.0.1
Requires (Dev)
- phpunit/phpunit: ^9
README
这个库有助于抽象API调用,无需在API调用中重新实现身份验证逻辑和分页逻辑。
安装
使用composer安装
$ composer require cognetif/ez-api
用法
- 创建一个新的类,该类扩展自
Cognetf\EzApi\ApiClient。 - 在调用
parent::__construct(Client $client)之后,在类构造函数中实现您的头或授权逻辑 - 使用[GET, POST, DELETE, PUT, PATCH]方法检索API结果并执行调用,例如
use GuzzleHttp\Client; use Cognetif\EzApi\ApiClient;
class MyClient extends ApiClient {
public function __construct(Client $client) {
parent::__construct($client);
$this->setBaseUrl('https://mydomain.com/api/')
->addHeader('Authorization', 'Bearer apkikey_hash')
->addHeader('Content-Type', 'application/json');
}
}
$myClient = new MyClient(new Client); $results = $myClient->get('/api/endpoint', ['param' => 'value']);
## Result Return
results are returned as an array with the following contract:
$results = [
'data' => [
//..Api Request Body
],
'error' => false
];
## Custom return logic
You can override how you class handles the returned data from the response by overriding the following function :
`ApiClient::handleResponse(ResponseInterface $response): array`
## Error message
If the api call returns a non-successful response code, the reason phrase will be available within the result array:
$results = [
'data' => [
//..Api Request Body
],
'error' => true,
'message' => '403 Forbidden'
];
## Running Tests
You can run tests via PhpUnit with the following command: `$ ./phpunit`.
There is a test report built to visualize the results and code coverage in `/Tests/Report`. Simply open the `index.html` or `dashboard.html` file in your local browser.