javis / json-api-client
一个简单的PHP JSON:API客户端库
v1.0.6
2020-03-05 20:26 UTC
Requires
- php: >=5.5.9
- guzzlehttp/guzzle: ~6.0
Requires (Dev)
- mockery/mockery: ^0.9
- phpunit/phpunit: ^4.8
This package is auto-updated.
Last update: 2024-09-06 08:48:58 UTC
README
用于轻松访问来自{json:api} API的数据的客户端。使用Guzzle或CURL等PHP HTTP客户端发送API请求需要编写大量代码。此包旨在简化此过程,允许将数据从API获取得尽可能简单,例如:
$client = new Client('http://my.api.com'); $response = $client->endpoint('users')->get(); return $response->data;
要求
- PHP >= 5.5.9
安装
composer require javis/json-api-client
使用
配置客户端
创建一个实例,传递基础URL和默认请求选项数组,其中您可以设置认证详情等。
$client = new Client('http://my.api.com',[ 'headers' => ['Authorization' => 'Bearer ' . $token] ]);
或传递已配置的GuzzleHttp\Client()
对象。
$http_client = new GuzzleHttp\Client(); $client = new Client('http://my.api.com',[], $http_client);
发送请求
- get($endpoint)
$client->endpoint('users')->get(); //get users
- post($endpoint)
$client->endpoint('users')->withJsonData([])->post();//store user
- patch($endpoint)
$client->endpoint('users')->withJsonData([])->patch();//do patch request
请求选项
$client->endpoint('users')->includes(['posts'])->get()
- 向请求URL添加查询参数include=posts
。请参阅https://jsonapi.fullstack.org.cn/format/#fetching-includes$client->endpoint('users')->fields(['user'=> ['id','name']])->get()
- 向查询参数添加fields[users]=id,name
。请参阅https://jsonapi.fullstack.org.cn/format/#fetching-sparse-fieldsets$client->endpoint('users')->filter(['users'=>['id'=>['eq'=>1]]])->get()
- 向查询参数添加filter[users][id][eq]=1
。{json:api}对于过滤是无知的,因此您可以选择您自己的过滤策略并传递任何您想要的数组。请参阅https://jsonapi.fullstack.org.cn/format/#fetching-filtering。$client->endpoint('users')->withQuery(['field'=>1])->get()
- 添加查询参数field=1=1
。理论上,添加过滤器、包含、字段和分页字段应该足够了。Client::limit($limit, $offset)->get('users')
- 向查询参数添加结果约束page[limit]=x&page[offet]=y
。请参阅https://jsonapi.fullstack.org.cn/format/#fetching-pagination$client->endpoint('users')->withFormData(['name'=>'John'])->post()
- 定义POST表单数据。表单数据可以包含文件,例如$client->endpoint('photos')->withFormData(['image'=> $request->file('image')])->post()
。$client->endpoint('users')->withJsonData(['name'=>'John'])->post()
- 定义POST JSON数据。
处理响应
请求将返回Response
对象。它将包含公共变量
$resopnse->data
- 包含响应数据。$resopnse->meta
- 包含响应元数据。$resopnse->errors
- 包含响应错误数据。$resopnse->status
- 保持请求的HTTP状态码。