Creating a client

The constructor of a client accepts an associative array of configuration options.

base_url

Configures a base URL for the client so that requests created using a relative URL are combined with the base_url of the client according to section 5.2 of RFC 3986.

  1. // Create a client with a base URL
  2. $client = new GuzzleHttp\Client(['base_url' => 'https://github.com']);
  3. // Send a request to https://github.com/notifications
  4. $response = $client->get('/notifications');

Don’t feel like reading RFC 3986? Here are some quick examples on how a base_url is resolved with another URI.

base_urlURIResult
http://foo.com/barhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/bar
http://foo.com/foobarhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/foo/bar
http://foo.comhttp://baz.comhttp://baz.com
http://foo.com/?barbarhttp://foo.com/bar

handler

Configures the RingPHP handler used to transfer the HTTP requests of a client. Guzzle will, by default, utilize a stacked handlers that chooses the best handler to use based on the provided request options and based on the extensions available in the environment.

message_factory

Specifies the factory used to create HTTP requests and responses (GuzzleHttp\Message\MessageFactoryInterface).

defaults

Associative array of Request Options that are applied to every request created by the client. This allows you to specify things like default headers (e.g., User-Agent), default query string parameters, SSL configurations, and any other supported request options.

emitter

Specifies an event emitter (GuzzleHttp\Event\EmitterInterface) instance to be used by the client to emit request events. This option is useful if you need to inject an emitter with listeners/subscribers already attached.

Here’s an example of creating a client with various options.

  1. use GuzzleHttp\Client;
  2. $client = new Client([
  3. 'base_url' => ['https://api.twitter.com/{version}/', ['version' => 'v1.1']],
  4. 'defaults' => [
  5. 'headers' => ['Foo' => 'Bar'],
  6. 'query' => ['testing' => '123'],
  7. 'auth' => ['username', 'password'],
  8. 'proxy' => 'tcp://localhost:80'
  9. ]
  10. ]);