stefna / api-client-runtime
API客户端的基础包
1.2.0
2024-04-11 14:27 UTC
Requires
- php: ^8.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.0
- psr/log: ^1.1 || ^2.0 || ^3.0
- starburst/utils: ^1.3
Requires (Dev)
- phpstan/phpstan: ^1.10
- stefna/codestyle: ^1.12.1
- stefna/http-client: ^1.0
Suggests
- kriswallsmith/buzz: For psr-18 implemenation
- nyholm/psr7: For psr-7 and psr-17 implemenations
README
基类,简化API创建
被Stefna OpenApi Generator等使用。
用法
要创建API客户端,你需要两个类
第一个是ServerConfiguration
类,其中包含你想要连接的API的信息
示例
class ServerConfiguration extends AbstractServerConfiguration { /** @var string[] */ protected array $serverUris = [ 'production' => 'https://api.example.com', 'staging' => 'https://staging.api.example.com', ]; protected string $selectedBaseUri = 'production'; protected SecurityScheme $securityScheme; protected SecurityValue $securityValue; public function __construct(SecurityValue $token) { $this->securityScheme = new ApiKeySecurityScheme('access-token', 'X-Api-Token', 'header'); $this->securityValue = $token; } public function getBaseUri(): string { return $this->serverUris[$this->selectedBaseUri]; } public function selectServer(string $name): void { $this->selectedBaseUri = $name; } public function getSecurityScheme(string $ref): ?SecurityScheme { return $this->securityScheme; } public function getSecurityValue(string $ref): ?SecurityValue { return $this->securityValue; } }
第二个是实际的API客户端
final class Service extends AbstractService { public function getNews(string $lang): array { $response = $this->doRequest(new \Stefna\ApiClientRuntime\Endpoint\Endpoint( 'GET', '/news/' . $lang, security: ['access-token'], )); return $this->parseJsonResponse($response); } public function sendNotification(string $to, string $from, string $text) { $response = $this->doRequest(new \Stefna\ApiClientRuntime\Endpoint\Endpoint( 'POST', '/notification', new \Stefna\ApiClientRuntime\RequestBody\JsonData([ 'to' => $to, 'from' => $from, 'text' => $text, ]), security: ['access-token'], )); return $this->parseJsonResponse($response); } public function sendPostData(array $postData): bool { $response = $this->doRequest(new \Stefna\ApiClientRuntime\Endpoint\Endpoint( 'POST', '/post-endpoint', new \Stefna\ApiClientRuntime\RequestBody\PostData($postData) security: ['access-token'], )); return $this->parseJsonResponse($response); } public static function createWithToken(string $token): self { return static::create(new ServerConfiguration(AuthSecurityValue::raw($token))); } }
消费API服务
当消费API客户端时,你可以通过两种不同的方法创建它
简单创建
简单的方法是使用静态的create
方法。
但是,为了使该方法正常工作,你需要安装nyholm/psr7
和kriswallsmith/buzz
,因为这是我们默认使用的psr实现
$service = Service::create(new ServerConfiguration(...)); // use service
使用自定义psr实现创建
如果你愿意,你可以提供自己的客户端和请求实现
$service = new Service( new ServerConfiguration(...), new GuzzleHttp\Client(), new GuzzleHttp\Psr7\HttpFactory(), );
许可证
查看附在此项目上的LICENSE文件。