Skip to content

Instantly share code, notes, and snippets.

@ozin7
Last active August 11, 2022 16:28
Show Gist options
  • Save ozin7/4499efcce02db08f291fe6e497cc55aa to your computer and use it in GitHub Desktop.
Save ozin7/4499efcce02db08f291fe6e497cc55aa to your computer and use it in GitHub Desktop.
ExampleApiClient example
services:
module_name.example.client:
class: Drupal\api_client_example\Service\ExampleApiClient
arguments:
- '@http_client'
<?php
namespace Drupal\api_client_example\Service;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Site\Settings;
use GuzzleHttp\ClientInterface;
/**
* Class ApiClientInterface.
*/
class ExampleApiClient {
// Endpoints.
const USERS_ENDPOINT = 'api/users';
const TOKEN_ENDPOINT = 'api/token';
// Domains.
const PROD_DOMAIN = 'https://domain.api.com';
const TEST_DOMAIN = 'https://domain.test.api.com';
const API_VERSION = '1.0';
/**
* Client configurations.
*
* @var array
*/
private array $configurations;
/**
* API token.
*/
private string $token;
/**
* ExampleApiClient constructor.
*/
public function __construct(private ClientInterface $httpClient) {
// Get from settings.php, env or any other storage.
$this->configurations = Settings::get('module_api_config', []);
}
/**
* Do request.
*/
private function doRequest(string $url, array $parameters = [], string $method = 'GET', array $success_codes = [200, 201]): array {
$parameters = $this->processParameters($parameters, $method);
try {
$response = $this->httpClient->request($method, $url, $parameters);
if (in_array($response->getStatusCode(), $success_codes)) {
$contents = $response->getBody()->getContents();
$json = Json::decode($contents);
return $json['data'];
}
}
catch (\Throwable $throwable) {
}
// Not good if we get here.
return [];
}
/**
* Get domain.
*/
private function getApiDomain(): string {
$domain = self::TEST_DOMAIN;
if ($this->configurations['prod_mode']) {
$domain = self::PROD_DOMAIN;
}
return sprintf('%s/%s', $domain, $this->getApiVersion());
}
/**
* Get api version.
*/
private function getApiVersion(): string {
return self::API_VERSION;
}
/**
* Process reauest parameters.
*/
private function processParameters(array $parameters, string $method): array {
$parameters['token'] = $this->getToken();
return $parameters;
}
/**
* Get users api data.
*/
public function getUsers(): array {
$url = sprintf('%s/%s', $this->getApiDomain(), self::USERS_ENDPOINT);
return $this->doRequest($url);
}
/**
* Refresh token.
*/
private function refreshToken(): string {
$url = sprintf('%s/%s', $this->getApiDomain(), self::TOKEN_ENDPOINT);
$response = $this->doRequest($url);
return $response['token'] ?? '';
}
/**
* Get token.
*/
private function getToken(): string {
// Check if token is expired here.
if (!$this->token) {
$this->token = $this->refreshToken();
}
return $this->token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment