Usage
Documentation for each method, request param, and response field are available via PHPDoc and will appear on hover in most modern editors.
Client
<?php
use Cloudflare\Client;
$client = new Client('CLOUDFLARE_TOKEN');
$response = $client->accounts()->list();
$results = $response->json();
Response
Every call to an API returns an instance of Cloudflare\HttpClient\Response
, which provides a variety of methods that may be used to inspect the response:
$response->body() : string;
$response->json($key = null, $default = null) : mixed;
$response->status() : int;
$response->successful() : bool;
$response->failed() : bool;
$response->toPsrResponse() : \Psr\Http\Message\ResponseInterface;
Error Handling
When the client is unable to connect to the API Cloudflare\HttpClient\Exceptions\ConnectionException
will be thrown.
If the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of Cloudflare\HttpClient\Exceptions\RequestException
will be thrown:
Status Code | Error Type |
---|---|
400 | BadRequestException |
401 | AuthenticationException |
403 | PermissionDeniedException |
404 | NotFoundException |
422 | UnprocessableEntityException |
429 | RateLimitException |
>=500 | InternalServerException |
N/A | RequestException |
The Cloudflare\HttpClient\Exceptions\RequestException
instance has a public $response property which will allow you to inspect the returned response.
Guzzle Middleware
Since PHP Client for Cloudflare API is powered by Guzzle, you may take advantage of Guzzle Middleware to manipulate the outgoing request or inspect the incoming response.
<?php
use Cloudflare\Client;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
$middlewares = [
function (callable $handler) {
return function (
RequestInterface $request,
array $options
) use ($handler) {
$promise = $handler($request, $options);
return $promise->then(
function (ResponseInterface $response) {
$header = $response->getHeader('X-Example');
// ...
return $response;
}
);
};
}
];
$client = new Client('CLOUDFLARE_TOKEN', $middlewares);
$response = $client->accounts()->list();
$results = $response->json();
Making custom/undocumented requests
This package provides convenient access to the Cloudflare REST API. If you need to access undocumented endpoints, the package can still be used.
<?php
use Cloudflare\Client;
$client = new Client('CLOUDFLARE_TOKEN');
$response = $client->getHttpClient()->get('/some/path', [
'some_query_arg' => 'bar'
]);
$results = $response->json();