tony-sol/symfony-api-client

适用于任何外部API的HTTP客户端

v1.0.0 2022-11-23 19:27 UTC

README

所需配置示例

ApiClient\Service\ApiClient:
    class: ApiClient\Service\ApiClient
    arguments:
        $httpClient: '@GuzzleHttp\ClientInterface'

ApiClient\Service\ApiClientInterface: '@ApiClient\Service\ApiClient'

使用示例

private \ApiClient\Service\ApiClientInterface $apiClient;

public function __construct(\ApiClient\Service\ApiClientInterface $apiClient)
{
    $this->apiClient = $apiClient;
}

public function sendGet()
{
    // curl --location --request GET 'http://example.org/endpoint?some=data'
    $response = $this->apiClient
        ->makeGetClient('http://example.org/endpoint')
        ->withResponseAs(Example\EndpoindDTO::class)
        ->withRequest(['some' => 'data',])
        ->send();

    /** @var int $responseCode */
    $responseCode = $response->getCode();
    /** @var array<string, string> $responseHeaders */
    $responseHeaders = $response->getHeaders();
    /** @var Example\EndpoindDTO $responseDTO */
    $responseDTO = $response->getResponse();
    return;
}

public function sendPost()
{
    // curl --location --request POST 'http://example.org/endpoint' --header 'Content-Type: application/json' --data-raw '{"some": "data"}'
    $response = $this->apiClient
        ->makePostClient('http://example.org/endpoint')
        ->withResponseAs(Example\EndpoindDTO::class)
        ->withRequest(['some' => 'data',])
        ->send();

    /** @var int $responseCode */
    $responseCode = $response->getCode();
    /** @var array<string, string> $responseHeaders */
    $responseHeaders = $response->getHeaders();
    /** @var Example\EndpoindDTO $responseDTO */
    $responseDTO = $response->getResponse();
    return;
}

免责声明

所有信息和源代码均以原样提供,不提供任何明示或暗示的保证。使用源代码或其部分完全由您自行决定,并承担风险。Citymobil LLC采取合理措施确保此存储库中发布的信息的相关性,但不承担维护或更新此存储库或其部分的责任,除非公司独立设立并通知第三方。

所有信息和源代码均以原始形式提供,不提供任何明确或暗示的保证。使用源代码或其任何部分完全由您自行决定并承担风险。公司“城市移动”有限责任公司采取合理措施确保存储库中发布的信息的相关性,但不承担维护或更新此存储库或其部分的责任,除非公司独立设立并通知第三方。