kielabokkie / laravel-guzzle-api-service
v0.3.2
2019-11-28 02:22 UTC
Requires
- guzzlehttp/guzzle: ^6.3
- rtheunissen/guzzle-log-middleware: ^0.4.2
Requires (Dev)
- laravel/framework: ~5.8.0|^6.0|^7.0
- orchestra/testbench: ^3.8|^4.0
- phpunit/phpunit: ^7.5
- symfony/var-dumper: ^4.1
README
注意:此包仍在开发中,尚未准备好生产使用。请自行承担风险!
安装
通过 composer 安装包
composer require kielabokkie/laravel-guzzle-api-service
包配置
运行以下命令发布配置文件
php artisan vendor:publish --provider="Kielabokkie\GuzzleApiService\GuzzleApiServiceProvider"
此文件的内容将在 config/api-service.php
中发布
return [ /* * Enable logging of request and responses to storage/logs/api-service.log */ 'logging_enabled' => env('API_SERVICE_LOGGING_ENABLED', false), /* * The namespace where your API Service classes are created under. * This will be appended to your base namespace. So the config below * will create a class under App\Support\Services. */ 'namespace' => 'Support\Services' ];
设置
要使用基础 API 客户端类,您需要添加所需的 $baseUrl
以设置 API 的基本 URL。您还必须在服务类的构造函数中调用 $this->setClient();
函数。
<?php namespace App\Support\Services; use Kielabokkie\GuzzleApiService\ApiClient; class HttpBinService extends ApiClient { protected $baseUrl = 'https://httpbin.org'; public function __construct() { $this->setClient(); } }
为了方便入门,您可以使用以下命令来生成 API 服务类
php artisan make:api-service HttpBinService
这将创建一个名为 HttpBinService.php
的类,位于 app/Support/Services
文件夹中。您只需设置 $baseUrl
,即可开始使用。
注意:如果您希望将类放置在其他位置,您可以在 api-service.php
配置文件中覆盖 namespace
变量。
用法
GET 请求
现在,要执行 GET 请求,您可以简单地执行以下操作
public function yourGetRequest() { $response = $this->get('/get')); return json_decode($response->getBody()->getContents()); }
这很简单,与您通常使用 Guzzle 执行 GET 请求的方式相同。
添加默认头信息
API 通常要求您在每次请求中添加特定的头信息,例如用于授权的目的。您无需在每次请求中作为选项传递这些信息,您可以在服务类的顶部添加以下函数
protected function defaultHeaders() { return [ 'Authorization' => 'Bearer abcdef123456', ]; }
添加默认查询参数
您可以使用类似的方式自动将默认查询参数添加到每个请求中
protected function defaultQueryParams() { return [ 'token' => 'your-token' ]; }
这将自动将令牌作为查询参数添加,例如:https://httpbin.org/get?token=your-token
。