Guzzle and PSR-7

Guzzle utilizes PSR-7 as the HTTP message interface. This allows Guzzle to workwith any other library that utilizes PSR-7 message interfaces.

Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTPresponses. Both requests and responses are referred to as messages.

Guzzle relies on the guzzlehttp/psr7 Composer package for its messageimplementation of PSR-7.

You can create a request using the GuzzleHttp\Psr7\Request class:

  1. use GuzzleHttp\Psr7\Request;
  2.  
  3. $request = new Request('GET', 'http://httpbin.org/get');
  4.  
  5. // You can provide other optional constructor arguments.
  6. $headers = ['X-Foo' => 'Bar'];
  7. $body = 'hello!';
  8. $request = new Request('PUT', 'http://httpbin.org/put', $headers, $body);

You can create a response using the GuzzleHttp\Psr7\Response class:

  1. use GuzzleHttp\Psr7\Response;
  2.  
  3. // The constructor requires no arguments.
  4. $response = new Response();
  5. echo $response->getStatusCode(); // 200
  6. echo $response->getProtocolVersion(); // 1.1
  7.  
  8. // You can supply any number of optional arguments.
  9. $status = 200;
  10. $headers = ['X-Foo' => 'Bar'];
  11. $body = 'hello!';
  12. $protocol = '1.1';
  13. $response = new Response($status, $headers, $body, $protocol);

Headers

Both request and response messages contain HTTP headers.

Accessing Headers

You can check if a request or response has a specific header using thehasHeader() method.

  1. use GuzzleHttp\Psr7;
  2.  
  3. $request = new Psr7\Request('GET', '/', ['X-Foo' => 'bar']);
  4.  
  5. if ($request->hasHeader('X-Foo')) {
  6. echo 'It is there';
  7. }

You can retrieve all the header values as an array of strings usinggetHeader().

  1. $request->getHeader('X-Foo'); // ['bar']
  2.  
  3. // Retrieving a missing header returns an empty array.
  4. $request->getHeader('X-Bar'); // []

You can iterate over the headers of a message using the getHeaders()method.

  1. foreach ($request->getHeaders() as $name => $values) {
  2. echo $name . ': ' . implode(', ', $values) . "\r\n";
  3. }

Complex Headers

Some headers contain additional key value pair information. For example, Linkheaders contain a link and several key value pairs:

  1. <http://foo.com>; rel="thing"; type="image/jpeg"

Guzzle provides a convenience feature that can be used to parse these types ofheaders:

  1. use GuzzleHttp\Psr7;
  2.  
  3. $request = new Psr7\Request('GET', '/', [
  4. 'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
  5. ]);
  6.  
  7. $parsed = Psr7\parse_header($request->getHeader('Link'));
  8. var_export($parsed);

Will output:

  1. array (
  2. 0 =>
  3. array (
  4. 0 => '<http:/.../front.jpeg>',
  5. 'rel' => 'front',
  6. 'type' => 'image/jpeg',
  7. ),
  8. )

The result contains a hash of key value pairs. Header values that have no key(i.e., the link) are indexed numerically while headers parts that form a keyvalue pair are added as a key value pair.

Body

Both request and response messages can contain a body.

You can retrieve the body of a message using the getBody() method:

  1. $response = GuzzleHttp\get('http://httpbin.org/get');
  2. echo $response->getBody();
  3. // JSON string: { ... }

The body used in request and response objects is aPsr\Http\Message\StreamInterface. This stream is used for bothuploading data and downloading data. Guzzle will, by default, store the body ofa message in a stream that uses PHP temp streams. When the size of the bodyexceeds 2 MB, the stream will automatically switch to storing data on diskrather than in memory (protecting your application from memory exhaustion).

The easiest way to create a body for a message is using the stream_forfunction from the GuzzleHttp\Psr7 namespace —GuzzleHttp\Psr7\stream_for. This function accepts strings, resources,callables, iterators, other streamables, and returns an instance ofPsr\Http\Message\StreamInterface.

The body of a request or response can be cast to a string or you can read andwrite bytes off of the stream as needed.

  1. use GuzzleHttp\Stream\Stream;
  2. $response = $client->request('GET', 'http://httpbin.org/get');
  3.  
  4. echo $response->getBody()->read(4);
  5. echo $response->getBody()->read(4);
  6. echo $response->getBody()->read(1024);
  7. var_export($response->eof());

Requests

Requests are sent from a client to a server. Requests include the method tobe applied to a resource, the identifier of the resource, and the protocolversion to use.

Request Methods

When creating a request, you are expected to provide the HTTP method you wishto perform. You can specify any method you'd like, including a custom methodthat might not be part of RFC 7231 (like "MOVE").

  1. // Create a request using a completely custom HTTP method
  2. $request = new \GuzzleHttp\Psr7\Request('MOVE', 'http://httpbin.org/move');
  3.  
  4. echo $request->getMethod();
  5. // MOVE

You can create and send a request using methods on a client that map to theHTTP method you wish to use.

GET
$client->get('http://httpbin.org/get&#39;, [/ options /])
POST
$client->post('http://httpbin.org/post&#39;, [/ options /])
HEAD
$client->head('http://httpbin.org/get&#39;, [/ options /])
PUT
$client->put('http://httpbin.org/put&#39;, [/ options /])
DELETE
$client->delete('http://httpbin.org/delete&#39;, [/ options /])
OPTIONS
$client->options('http://httpbin.org/get&#39;, [/ options /])
PATCH
$client->patch('http://httpbin.org/put&#39;, [/ options /])
For example:

  1. $response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);

Request URI

The request URI is represented by a Psr\Http\Message\UriInterface object.Guzzle provides an implementation of this interface using theGuzzleHttp\Psr7\Uri class.

When creating a request, you can provide the URI as a string or an instance ofPsr\Http\Message\UriInterface.

  1. $response = $client->request('GET', 'http://httpbin.org/get?q=foo');

Scheme

The scheme of a requestspecifies the protocol to use when sending the request. When using Guzzle, thescheme can be set to "http" or "https".

  1. $request = new Request('GET', 'http://httpbin.org');
  2. echo $request->getUri()->getScheme(); // http
  3. echo $request->getUri(); // http://httpbin.org

Host

The host is accessible using the URI owned by the request or by accessing theHost header.

  1. $request = new Request('GET', 'http://httpbin.org');
  2. echo $request->getUri()->getHost(); // httpbin.org
  3. echo $request->getHeader('Host'); // httpbin.org

Port

No port is necessary when using the "http" or "https" schemes.

  1. $request = new Request('GET', 'http://httpbin.org:8080');
  2. echo $request->getUri()->getPort(); // 8080
  3. echo $request->getUri(); // http://httpbin.org:8080

Path

The path of a request is accessible via the URI object.

  1. $request = new Request('GET', 'http://httpbin.org/get');
  2. echo $request->getUri()->getPath(); // /get

The contents of the path will be automatically filtered to ensure that onlyallowed characters are present in the path. Any characters that are not allowedin the path will be percent-encoded according toRFC 3986 section 3.3

Query string

The query string of a request can be accessed using the getQuery() of theURI object owned by the request.

  1. $request = new Request('GET', 'http://httpbin.org/?foo=bar');
  2. echo $request->getUri()->getQuery(); // foo=bar

The contents of the query string will be automatically filtered to ensure thatonly allowed characters are present in the query string. Any characters thatare not allowed in the query string will be percent-encoded according toRFC 3986 section 3.4

Responses

Responses are the HTTP messages a client receives from a server after sendingan HTTP request message.

Start-Line

The start-line of a response contains the protocol and protocol version,status code, and reason phrase.

  1. $client = new \GuzzleHttp\Client();
  2. $response = $client->request('GET', 'http://httpbin.org/get');
  3.  
  4. echo $response->getStatusCode(); // 200
  5. echo $response->getReasonPhrase(); // OK
  6. echo $response->getProtocolVersion(); // 1.1

Body

As described earlier, you can get the body of a response using thegetBody() method.

  1. $body = $response->getBody();
  2. echo $body;
  3. // Cast to a string: { ... }
  4. $body->seek(0);
  5. // Rewind the body
  6. $body->read(1024);
  7. // Read bytes of the body

Streams

Guzzle uses PSR-7 stream objects to represent request and response messagebodies. These stream objects allow you to work with various types of data allusing a common interface.

HTTP messages consist of a start-line, headers, and a body. The body of an HTTPmessage can be very small or extremely large. Attempting to represent the bodyof a message as a string can easily consume more memory than intended becausethe body must be stored completely in memory. Attempting to store the body of arequest or response in memory would preclude the use of that implementation frombeing able to work with large message bodies. The StreamInterface is used inorder to hide the implementation details of where a stream of data is read fromor written to.

The PSR-7 Psr\Http\Message\StreamInterface exposes several methodsthat enable streams to be read from, written to, and traversed effectively.

Streams expose their capabilities using three methods: isReadable(),isWritable(), and isSeekable(). These methods can be used by streamcollaborators to determine if a stream is capable of their requirements.

Each stream instance has various capabilities: they can be read-only,write-only, read-write, allow arbitrary random access (seeking forwards orbackwards to any location), or only allow sequential access (for example in thecase of a socket or pipe).

Guzzle uses the guzzlehttp/psr7 package to provide stream support. Moreinformation on using streams, creating streams, converting streams to PHPstream resource, and stream decorators can be found in theGuzzle PSR-7 documentation.

Creating Streams

The best way to create a stream is using the GuzzleHttp\Psr7\stream_forfunction. This function accepts strings, resources returned from fopen(),an object that implements __toString(), iterators, callables, and instancesof Psr\Http\Message\StreamInterface.

  1. use GuzzleHttp\Psr7;
  2.  
  3. $stream = Psr7\stream_for('string data');
  4. echo $stream;
  5. // string data
  6. echo $stream->read(3);
  7. // str
  8. echo $stream->getContents();
  9. // ing data
  10. var_export($stream->eof());
  11. // true
  12. var_export($stream->tell());
  13. // 11

You can create streams from iterators. The iterator can yield any number ofbytes per iteration. Any excess bytes returned by the iterator that were notrequested by a stream consumer will be buffered until a subsequent read.

  1. use GuzzleHttp\Psr7;
  2.  
  3. $generator = function ($bytes) {
  4. for ($i = 0; $i < $bytes; $i++) {
  5. yield '.';
  6. }
  7. };
  8.  
  9. $iter = $generator(1024);
  10. $stream = Psr7\stream_for($iter);
  11. echo $stream->read(3); // ...

Metadata

Streams expose stream metadata through the getMetadata() method. Thismethod provides the data you would retrieve when calling PHP'sstream_get_meta_data() function,and can optionally expose other custom data.

  1. use GuzzleHttp\Psr7;
  2.  
  3. $resource = fopen('/path/to/file', 'r');
  4. $stream = Psr7\stream_for($resource);
  5. echo $stream->getMetadata('uri');
  6. // /path/to/file
  7. var_export($stream->isReadable());
  8. // true
  9. var_export($stream->isWritable());
  10. // false
  11. var_export($stream->isSeekable());
  12. // true

Stream Decorators

Adding custom functionality to streams is very simple with stream decorators.Guzzle provides several built-in decorators that provide additional streamfunctionality.