1
=============================
2
Request and Response Messages
3
=============================
5
Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP
6
responses. Both requests and responses are referred to as messages.
11
Both request and response messages contain HTTP headers.
16
Some headers contain additional key value pair information. For example, Link
17
headers contain a link and several key value pairs:
21
<http://foo.com>; rel="thing"; type="image/jpeg"
23
Guzzle provides a convenience feature that can be used to parse these types of
28
use GuzzleHttp\Message\Request;
30
$request = new Request('GET', '/', [
31
'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
34
$parsed = Request::parseHeader($request, 'Link');
35
echo json_encode($parsed, JSON_PRETTY_PRINT);
41
"0": "<http:\/...\/front.jpeg>",
47
The result contains a hash of key value pairs. Header values that have no key
48
(i.e., the link) are indexed numerically while headers parts that form a key
49
value pair are added as a key value pair.
51
See :ref:`headers` for information on how the headers of a request and response
52
can be accessed and modified.
57
Both request and response messages can contain a body.
59
You can check to see if a request or response has a body using the
64
$response = GuzzleHttp\get('http://httpbin.org/get');
65
if ($response->getBody()) {
66
echo $response->getBody();
67
// JSON string: { ... }
70
The body used in request and response objects is a
71
``GuzzleHttp\Stream\StreamInterface``. This stream is used for both uploading
72
data and downloading data. Guzzle will, by default, store the body of a message
73
in a stream that uses PHP temp streams. When the size of the body exceeds
74
2 MB, the stream will automatically switch to storing data on disk rather than
75
in memory (protecting your application from memory exhaustion).
77
You can change the body used in a request or response using the ``setBody()``
82
use GuzzleHttp\Stream\Stream;
83
$request = $client->createRequest('PUT', 'http://httpbin.org/put');
84
$request->setBody(Stream::factory('foo'));
86
The easiest way to create a body for a request is using the static
87
``GuzzleHttp\Stream\Stream::factory()`` method. This method accepts various
88
inputs like strings, resources returned from ``fopen()``, and other
89
``GuzzleHttp\Stream\StreamInterface`` objects.
91
The body of a request or response can be cast to a string or you can read and
92
write bytes off of the stream as needed.
96
use GuzzleHttp\Stream\Stream;
97
$request = $client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'testing...']);
99
echo $request->getBody()->read(4);
101
echo $request->getBody()->read(4);
103
echo $request->getBody()->read(1024);
105
var_export($request->eof());
108
You can find out more about Guzzle stream objects in :doc:`streams`.
113
Requests are sent from a client to a server. Requests include the method to
114
be applied to a resource, the identifier of the resource, and the protocol
117
Clients are used to create request messages. More precisely, clients use
118
a ``GuzzleHttp\Message\MessageFactoryInterface`` to create request messages.
119
You create requests with a client using the ``createRequest()`` method.
123
// Create a request but don't send it immediately
124
$request = $client->createRequest('GET', 'http://httpbin.org/get');
129
When creating a request, you are expected to provide the HTTP method you wish
130
to perform. You can specify any method you'd like, including a custom method
131
that might not be part of RFC 2616 (like "MOVE").
135
// Create a request using a completely custom HTTP method
136
$request = $client->createRequest('MOVE', 'http://httpbin.org/move', ['exceptions' => false]);
138
echo $request->getMethod();
141
$response = $client->send($request);
142
echo $response->getStatusCode();
145
You can create and send a request using methods on a client that map to the
146
HTTP method you wish to use.
148
:GET: ``$client->get('http://httpbin.org/get', [/** options **/])``
149
:POST: ``$client->post('http://httpbin.org/post', [/** options **/])``
150
:HEAD: ``$client->head('http://httpbin.org/get', [/** options **/])``
151
:PUT: ``$client->put('http://httpbin.org/put', [/** options **/])``
152
:DELETE: ``$client->delete('http://httpbin.org/delete', [/** options **/])``
153
:OPTIONS: ``$client->options('http://httpbin.org/get', [/** options **/])``
154
:PATCH: ``$client->patch('http://httpbin.org/put', [/** options **/])``
158
$response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);
163
The resource you are requesting with an HTTP request is identified by the
164
path of the request, the query string, and the "Host" header of the request.
166
When creating a request, you can provide the entire resource URI as a URL.
170
$response = $client->get('http://httbin.org/get?q=foo');
172
Using the above code, you will send a request that uses ``httpbin.org`` as
173
the Host header, sends the request over port 80, uses ``/get`` as the path,
174
and sends ``?q=foo`` as the query string. All of this is parsed automatically
175
from the provided URI.
177
Sometimes you don't know what the entire request will be when it is created.
178
In these cases, you can modify the request as needed before sending it using
179
the ``createRequest()`` method of the client and methods on the request that
180
allow you to change it.
184
$request = $client->createRequest('GET', 'http://httbin.org');
186
You can change the path of the request using ``setPath()``:
190
$request->setPath('/get');
191
echo $request->getPath();
193
echo $request->getUrl();
194
// http://httpbin.com/get
199
The `scheme <http://tools.ietf.org/html/rfc3986#section-3.1>`_ of a request
200
specifies the protocol to use when sending the request. When using Guzzle, the
201
scheme can be set to "http" or "https".
203
You can change the scheme of the request using the ``setScheme()`` method:
207
$request = $client->createRequest('GET', 'http://httbin.org');
208
$request->setScheme('https');
209
echo $request->getScheme();
211
echo $request->getUrl();
212
// https://httpbin.com/get
217
No port is necessary when using the "http" or "https" schemes, but you can
218
override the port using ``setPort()``. If you need to modify the port used with
219
the specified scheme from the default setting, then you must use the
220
``setPort()`` method.
224
$request = $client->createRequest('GET', 'http://httbin.org');
225
$request->setPort(8080);
226
echo $request->getPort();
228
echo $request->getUrl();
229
// https://httpbin.com:8080/get
231
// Set the port back to the default value for the scheme
232
$request->setPort(443);
233
echo $request->getUrl();
234
// https://httpbin.com/get
239
You can get the query string of the request using the ``getQuery()`` method.
240
This method returns a ``GuzzleHttp\Query`` object. A Query object can be
241
accessed like a PHP array, iterated in a foreach statement like a PHP array,
242
and cast to a string.
246
$request = $client->createRequest('GET', 'http://httbin.org');
247
$query = $request->getQuery();
248
$query['foo'] = 'bar';
249
$query['baz'] = 'bam';
250
$query['bam'] = ['test' => 'abc'];
252
echo $request->getQuery();
253
// foo=bar&baz=bam&bam%5Btest%5D=abc
255
echo $request->getQuery()['foo'];
257
echo $request->getQuery()->get('foo');
259
echo $request->getQuery()->get('foo');
262
var_export($request->getQuery()['bam']);
263
// array('test' => 'abc')
265
foreach ($query as $key => $value) {
269
echo $request->getUrl();
270
// https://httpbin.com/get?foo=bar&baz=bam&bam%5Btest%5D=abc
275
Query objects can store scalar values or arrays of values. When an array of
276
values is added to a query object, the query object uses a query aggregator to
277
convert the complex structure into a string. Query objects will use
278
`PHP style query strings <http://www.php.net/http_build_query>`_ when complex
279
query string parameters are converted to a string. You can customize how
280
complex query string parameters are aggregated using the ``setAggregator()``
281
method of a query string object.
285
$query->setAggregator($query::duplicateAggregator());
287
In the above example, we've changed the query object to use the
288
"duplicateAggregator". This aggregator will allow duplicate entries to appear
289
in a query string rather than appending "[n]" to each value. So if you had a
290
query string with ``['a' => ['b', 'c']]``, the duplicate aggregator would
291
convert this to "a=b&a=c" while the default aggregator would convert this to
292
"a[0]=b&a[1]=c" (with urlencoded brackets).
294
The ``setAggregator()`` method accepts a ``callable`` which is used to convert
295
a deeply nested array of query string variables into a flattened array of key
296
value pairs. The callable accepts an array of query data and returns a
297
flattened array of key value pairs where each value is an array of strings.
298
You can use the ``GuzzleHttp\Query::walkQuery()`` static function to easily
299
create custom query aggregators.
304
You can change the host header of the request in a predictable way using the
305
``setHost()`` method of a request:
309
$request->setHost('www.google.com');
310
echo $request->getHost();
312
echo $request->getUrl();
313
// https://www.google.com/get?foo=bar&baz=bam
317
The Host header can also be changed by modifying the Host header of a
318
request directly, but modifying the Host header directly could result in
319
sending a request to a different Host than what is specified in the Host
320
header (sometimes this is actually the desired behavior).
325
You can use the ``getResource()`` method of a request to return the path and
326
query string of a request in a single string.
330
$request = $client->createRequest('GET', 'http://httpbin.org/get?baz=bar');
331
echo $request->getResource();
337
Request messages contain a configuration collection that can be used by
338
event listeners and HTTP adapters to modify how a request behaves or is
339
transferred over the wire. For example, many of the request options that are
340
specified when creating a request are actually set as config options that are
341
only acted upon by adapters and listeners when the request is sent.
343
You can get access to the request's config object using the ``getConfig()``
348
$request = $client->createRequest('GET', '/');
349
$config = $request->getConfig();
351
The config object is a ``GuzzleHttp\Common\Collection`` object that acts like
352
an associative array. You can grab values from the collection using array like
353
access. You can also modify and remove values using array like access.
357
$config['foo'] = 'bar';
361
var_export(isset($config['foo']));
364
unset($config['foo']);
365
var_export(isset($config['foo']));
368
var_export($config['foo']);
371
HTTP adapters and event listeners can expose additional customization options
372
through request config settings. For example, in order to specify custom cURL
373
options to the cURL adapter, you need to specify an associative array in the
374
``curl`` ``config`` request option.
381
CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
382
CURLOPT_USERPWD => 'username:password'
387
Consult the HTTP adapters and event listeners you are using to see if they
388
allow customization through request configuration options.
393
Request objects implement ``GuzzleHttp\Common\HasEmitterInterface``, so they
394
have a method called ``getEmitter()`` that can be used to get an event emitter
395
used by the request. Any listener or subscriber attached to a request will only
396
be triggered for the lifecycle events of a specific request. Conversely, adding
397
an event listener or subscriber to a client will listen to all lifecycle events
398
of all requests created by the client.
400
See :doc:`events` for more information.
405
Responses are the HTTP messages a client receives from a server after sending
406
an HTTP request message.
411
The start-line of a response contains the protocol and protocol version,
412
status code, and reason phrase.
416
$response = GuzzleHttp\get('http://httpbin.org/get');
417
echo $response->getStatusCode();
419
echo $response->getReasonPhrase();
421
echo $response->getProtocolVersion();
427
As described earlier, you can get the body of a response using the
428
``getBody()`` method.
432
if ($body = $response->getBody()) {
434
// Cast to a string: { ... }
438
// Read bytes of the body
441
When working with JSON responses, you can use the ``json()`` method of a
446
$json = $response->json();
450
Guzzle uses the ``json_decode()`` method of PHP and uses arrays rather than
451
``stdClass`` objects for objects.
453
You can use the ``xml()`` method when working with XML data.
457
$xml = $response->xml();
461
Guzzle uses the ``SimpleXMLElement`` objects when converting response
467
The URL that was ultimately accessed that returned a response can be accessed
468
using the ``getEffectiveUrl()`` method of a response. This method will return
469
the URL of a request or the URL of the last redirected URL if any redirects
470
occurred while transferring a request.
474
$response = GuzzleHttp\get('http://httpbin.org/get');
475
echo $response->getEffectiveUrl();
476
// http://httpbin.org/get
478
$response = GuzzleHttp\get('http://httpbin.org/redirect-to?url=http://www.google.com');
479
echo $response->getEffectiveUrl();
480
// http://www.google.com