Class Client
The end user interface for doing HTTP requests.
Scoped clients
If you're doing multiple requests to the same hostname it's often convenient to use the constructor arguments to create a scoped client. This allows you to keep your code DRY and not repeat hostnames, authentication, and other options.
Doing requests
Once you've created an instance of Client you can do requests using several methods. Each corresponds to a different HTTP method.
- get()
- post()
- put()
- delete()
- patch()
Cookie management
Client will maintain cookies from the responses done with
a client instance. These cookies will be automatically added
to future requests to matching hosts. Cookies will respect the
Expires, Path and Domain attributes. You can get the client's
CookieCollection using cookies()
You can use the 'cookieJar' constructor option to provide a custom cookie jar instance you've restored from cache/disk. By default, an empty instance of {@link \Cake\Http\Client\CookieCollection} will be created.
Sending request bodies
By default, any POST/PUT/PATCH/DELETE request with $data will
send their data as application/x-www-form-urlencoded unless
there are attached files. In that case multipart/form-data
will be used.
When sending request bodies you can use the type option to
set the Content-Type for the request:
$http->get('/users', [], ['type' => 'json']);The type option sets both the Content-Type and Accept header, to
the same mime type. When using type you can use either a full mime
type or an alias. If you need different types in the Accept and Content-Type
headers you should set them manually and not use type
Using authentication
By using the auth key you can use authentication. The type sub option
can be used to specify which authentication strategy you want to use.
CakePHP comes with a few built-in strategies:
- Basic
- Digest
- Oauth
Using proxies
By using the proxy key you can set authentication credentials for
a proxy if you need to use one. The type sub option can be used to
specify which authentication strategy you want to use.
CakePHP comes with built-in support for basic authentication.
Property Summary
- 
        $_adapter protectedCake\Http\Client\AdapterInterfaceAdapter for sending requests. 
- 
        $_config protectedarray<string, mixed>Runtime config 
- 
        $_configInitialized protectedboolWhether the config property has already been configured with defaults 
- 
        $_cookies protectedCake\Http\Cookie\CookieCollectionList of cookies from responses made with this client. 
- 
        $_defaultConfig protectedarray<string, mixed>Default configuration for the client. 
- 
        $_mockAdapter protected staticCake\Http\Client\Adapter\Mock|nullMock adapter for stubbing requests in tests. 
Method Summary
- 
          __construct() publicCreate a new HTTP Client. 
- 
          _addAuthentication() protectedAdd authentication headers to the request. 
- 
          _addProxy() protectedAdd proxy authentication headers. 
- 
          _configDelete() protectedDeletes a single config key. 
- 
          _configRead() protectedReads a config key. 
- 
          _configWrite() protectedWrites a config key. 
- 
          _createAuth() protectedCreate the authentication strategy. 
- 
          _createRequest() protectedCreates a new request object based on the parameters. 
- 
          _doRequest() protectedHelper method for doing non-GET requests. 
- 
          _mergeOptions() protectedDoes a recursive merge of the parameter with the scope config. 
- 
          _sendRequest() protectedSend a request without redirection. 
- 
          _typeHeaders() protectedReturns headers for Accept/Content-Type based on a short type or full mime-type. 
- 
          addCookie() publicAdds a cookie to the Client collection. 
- 
          addMockResponse() public staticAdd a mocked response. 
- 
          buildUrl() publicGenerate a URL based on the scoped client options. 
- 
          clearMockResponses() public staticClear all mocked responses 
- 
          configShallow() publicMerge provided config with existing config. Unlike config()which does a recursive merge for nested keys, this method does a simple merge.
- 
          cookies() publicGet the cookies stored in the Client. 
- 
          createFromUrl() public staticClient instance returned is scoped to the domain, port, and scheme parsed from the passed URL string. The passed string must have a scheme and a domain. Optionally, if a port is included in the string, the port will be scoped too. If a path is included in the URL, the client instance will build urls with it prepended. Other parts of the url string are ignored. 
- 
          delete() publicDo a DELETE request. 
- 
          get() publicDo a GET request. 
- 
          getConfig() publicReturns the config. 
- 
          getConfigOrFail() publicReturns the config for this specific key. 
- 
          head() publicDo a HEAD request. 
- 
          options() publicDo an OPTIONS request. 
- 
          patch() publicDo a PATCH request. 
- 
          post() publicDo a POST request. 
- 
          put() publicDo a PUT request. 
- 
          send() publicSend a request. 
- 
          sendRequest() publicSends a PSR-7 request and returns a PSR-7 response. 
- 
          setConfig() publicSets the config. 
- 
          trace() publicDo a TRACE request. 
Method Detail
__construct() ¶ public
__construct(array<string, mixed> $config = [])Create a new HTTP Client.
Config options
You can set the following options when creating a client:
- host - The hostname to do requests on.
- port - The port to use.
- scheme - The default scheme/protocol to use. Defaults to http.
- basePath - A path to append to the domain to use. (/api/v1/)
- timeout - The timeout in seconds. Defaults to 30
- ssl_verify_peer - Whether SSL certificates should be validated. Defaults to true.
- ssl_verify_peer_name - Whether peer names should be validated. Defaults to true.
- ssl_verify_depth - The maximum certificate chain depth to traverse. Defaults to 5.
- ssl_verify_host - Verify that the certificate and hostname match. Defaults to true.
- redirect - Number of redirects to follow. Defaults to false.
- adapter - The adapter class name or instance. Defaults to
\Cake\Http\Client\Adapter\Curl if curlextension is loaded else \Cake\Http\Client\Adapter\Stream.
- protocolVersion - The HTTP protocol version to use. Defaults to 1.1
- auth - The authentication credentials to use. If a usernameandpasswordkey are provided without atypekey Basic authentication will be assumed. You can use thetypekey to define the authentication adapter classname to use. Short class names are resolved to theHttp\Client\Authnamespace.
Parameters
- 
                array<string, mixed>$config optional
- Config options for scoped clients. 
_addAuthentication() ¶ protected
_addAuthentication(Cake\Http\Client\Request $request, array<string, mixed> $options): Cake\Http\Client\RequestAdd authentication headers to the request.
Uses the authentication type to choose the correct strategy and use its methods to add headers.
Parameters
- 
                Cake\Http\Client\Request$request
- The request to modify. 
- 
                array<string, mixed>$options
- Array of options containing the 'auth' key. 
Returns
Cake\Http\Client\RequestThe updated request object.
_addProxy() ¶ protected
_addProxy(Cake\Http\Client\Request $request, array<string, mixed> $options): Cake\Http\Client\RequestAdd proxy authentication headers.
Uses the authentication type to choose the correct strategy and use its methods to add headers.
Parameters
- 
                Cake\Http\Client\Request$request
- The request to modify. 
- 
                array<string, mixed>$options
- Array of options containing the 'proxy' key. 
Returns
Cake\Http\Client\RequestThe updated request object.
_configDelete() ¶ protected
_configDelete(string $key): voidDeletes a single config key.
Parameters
- 
                string$key
- Key to delete. 
Returns
voidThrows
Cake\Core\Exception\CakeExceptionif attempting to clobber existing config
_configRead() ¶ protected
_configRead(string|null $key): mixedReads a config key.
Parameters
- 
                string|null$key
- Key to read. 
Returns
mixed_configWrite() ¶ protected
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): voidWrites a config key.
Parameters
- 
                array<string, mixed>|string$key
- Key to write to. 
- 
                mixed$value
- Value to write. 
- 
                string|bool$merge optional
- True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false. 
Returns
voidThrows
Cake\Core\Exception\CakeExceptionif attempting to clobber existing config
_createAuth() ¶ protected
_createAuth(array $auth, array<string, mixed> $options): objectCreate the authentication strategy.
Use the configuration options to create the correct authentication strategy handler.
Parameters
- 
                array$auth
- The authentication options to use. 
- 
                array<string, mixed>$options
- The overall request options to use. 
Returns
objectAuthentication strategy instance.
Throws
Cake\Core\Exception\CakeExceptionwhen an invalid strategy is chosen.
_createRequest() ¶ protected
_createRequest(string $method, string $url, mixed $data, array<string, mixed> $options): Cake\Http\Client\RequestCreates a new request object based on the parameters.
Parameters
- 
                string$method
- HTTP method name. 
- 
                string$url
- The url including query string. 
- 
                mixed$data
- The request body. 
- 
                array<string, mixed>$options
- The options to use. Contains auth, proxy, etc. 
Returns
Cake\Http\Client\Request_doRequest() ¶ protected
_doRequest(string $method, string $url, mixed $data, array<string, mixed> $options): Cake\Http\Client\ResponseHelper method for doing non-GET requests.
Parameters
- 
                string$method
- HTTP method. 
- 
                string$url
- URL to request. 
- 
                mixed$data
- The request body. 
- 
                array<string, mixed>$options
- The options to use. Contains auth, proxy, etc. 
Returns
Cake\Http\Client\Response_mergeOptions() ¶ protected
_mergeOptions(array<string, mixed> $options): arrayDoes a recursive merge of the parameter with the scope config.
Parameters
- 
                array<string, mixed>$options
- Options to merge. 
Returns
arrayOptions merged with set config.
_sendRequest() ¶ protected
_sendRequest(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): Cake\Http\Client\ResponseSend a request without redirection.
Parameters
- 
                Psr\Http\Message\RequestInterface$request
- The request to send. 
- 
                array<string, mixed>$options
- Additional options to use. 
Returns
Cake\Http\Client\Response_typeHeaders() ¶ protected
_typeHeaders(string $type): array<string, string>Returns headers for Accept/Content-Type based on a short type or full mime-type.
Parameters
- 
                string$type
- short type alias or full mimetype. 
Returns
array<string, string>Headers to set on the request.
Throws
Cake\Core\Exception\CakeExceptionWhen an unknown type alias is used.
addCookie() ¶ public
addCookie(Cake\Http\Cookie\CookieInterface $cookie): $thisAdds a cookie to the Client collection.
Parameters
- 
                Cake\Http\Cookie\CookieInterface$cookie
- Cookie object. 
Returns
$thisThrows
InvalidArgumentExceptionaddMockResponse() ¶ public static
addMockResponse(string $method, string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): voidAdd a mocked response.
Mocked responses are stored in an adapter that is called before the network adapter is called.
Matching Requests
TODO finish this.
Options
- matchAn additional closure to match requests with.
Parameters
- 
                string$method
- The HTTP method being mocked. 
- 
                string$url
- The URL being matched. See above for examples. 
- 
                Cake\Http\Client\Response$response
- The response that matches the request. 
- 
                array<string, mixed>$options optional
- See above. 
Returns
voidbuildUrl() ¶ public
buildUrl(string $url, array|string $query = [], array<string, mixed> $options = []): stringGenerate a URL based on the scoped client options.
Parameters
- 
                string$url
- Either a full URL or just the path. 
- 
                array|string$query optional
- The query data for the URL. 
- 
                array<string, mixed>$options optional
- The config options stored with Client::config() 
Returns
stringA complete url with scheme, port, host, and path.
clearMockResponses() ¶ public static
clearMockResponses(): voidClear all mocked responses
Returns
voidconfigShallow() ¶ public
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $thisMerge provided config with existing config. Unlike config() which does
a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
$this->configShallow('key', $value);Setting a nested value:
$this->configShallow('some.nested.key', $value);Updating multiple config settings at the same time:
$this->configShallow(['one' => 'value', 'another' => 'value']);Parameters
- 
                array<string, mixed>|string$key
- The key to set, or a complete array of configs. 
- 
                mixed|null$value optional
- The value to set. 
Returns
$thiscookies() ¶ public
cookies(): Cake\Http\Cookie\CookieCollectionGet the cookies stored in the Client.
Returns
Cake\Http\Cookie\CookieCollectioncreateFromUrl() ¶ public static
createFromUrl(string $url): staticClient instance returned is scoped to the domain, port, and scheme parsed from the passed URL string. The passed string must have a scheme and a domain. Optionally, if a port is included in the string, the port will be scoped too. If a path is included in the URL, the client instance will build urls with it prepended. Other parts of the url string are ignored.
Parameters
- 
                string$url
- A string URL e.g. https://example.com 
Returns
staticThrows
InvalidArgumentExceptiondelete() ¶ public
delete(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a DELETE request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                mixed$data optional
- The request data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\Responseget() ¶ public
get(string $url, array|string $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a GET request.
The $data argument supports a special _content key
for providing a request body in a GET request. This is
generally not used, but services like ElasticSearch use
this feature.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                array|string$data optional
- The query data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\ResponsegetConfig() ¶ public
getConfig(string|null $key = null, mixed $default = null): mixedReturns the config.
Usage
Reading the whole config:
$this->getConfig();Reading a specific value:
$this->getConfig('key');Reading a nested value:
$this->getConfig('some.nested.key');Reading with default value:
$this->getConfig('some-key', 'default-value');Parameters
- 
                string|null$key optional
- The key to get or null for the whole config. 
- 
                mixed$default optional
- The return value when the key does not exist. 
Returns
mixedConfiguration data at the named key or null if the key does not exist.
getConfigOrFail() ¶ public
getConfigOrFail(string $key): mixedReturns the config for this specific key.
The config value for this key must exist, it can never be null.
Parameters
- 
                string$key
- The key to get. 
Returns
mixedConfiguration data at the named key
Throws
InvalidArgumentExceptionhead() ¶ public
head(string $url, array $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a HEAD request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                array$data optional
- The query string data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\Responseoptions() ¶ public
options(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo an OPTIONS request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                mixed$data optional
- The request data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\Responsepatch() ¶ public
patch(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a PATCH request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                mixed$data optional
- The request data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\Responsepost() ¶ public
post(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a POST request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                mixed$data optional
- The post data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\Responseput() ¶ public
put(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a PUT request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                mixed$data optional
- The request data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\Responsesend() ¶ public
send(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options = []): Cake\Http\Client\ResponseSend a request.
Used internally by other methods, but can also be used to send handcrafted Request objects.
Parameters
- 
                Psr\Http\Message\RequestInterface$request
- The request to send. 
- 
                array<string, mixed>$options optional
- Additional options to use. 
Returns
Cake\Http\Client\ResponsesendRequest() ¶ public
sendRequest(RequestInterface $request): Psr\Http\Message\ResponseInterfaceSends a PSR-7 request and returns a PSR-7 response.
Parameters
- 
                RequestInterface$request
- Request instance. 
Returns
Psr\Http\Message\ResponseInterfaceResponse instance.
Throws
Psr\Http\Client\ClientExceptionInterfaceIf an error happens while processing the request.
setConfig() ¶ public
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $thisSets the config.
Usage
Setting a specific value:
$this->setConfig('key', $value);Setting a nested value:
$this->setConfig('some.nested.key', $value);Updating multiple config settings at the same time:
$this->setConfig(['one' => 'value', 'another' => 'value']);Parameters
- 
                array<string, mixed>|string$key
- The key to set, or a complete array of configs. 
- 
                mixed|null$value optional
- The value to set. 
- 
                bool$merge optional
- Whether to recursively merge or overwrite existing config, defaults to true. 
Returns
$thisThrows
Cake\Core\Exception\CakeExceptionWhen trying to set a key that is invalid.
trace() ¶ public
trace(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\ResponseDo a TRACE request.
Parameters
- 
                string$url
- The url or path you want to request. 
- 
                mixed$data optional
- The request data you want to send. 
- 
                array<string, mixed>$options optional
- Additional options for the request. 
Returns
Cake\Http\Client\ResponseProperty Detail
$_configInitialized ¶ protected
Whether the config property has already been configured with defaults
Type
bool$_cookies ¶ protected
List of cookies from responses made with this client.
Cookies are indexed by the cookie's domain or request host name.
Type
Cake\Http\Cookie\CookieCollection$_mockAdapter ¶ protected static
Mock adapter for stubbing requests in tests.
Type
Cake\Http\Client\Adapter\Mock|null