Handlers and Middleware

Guzzle clients use a handler and middleware system to send HTTP requests.

Handlers

A handler function accepts a Psr\Http\Message\RequestInterface and array of request options and returns a GuzzleHttp\Promise\PromiseInterface that is fulfilled with a Psr\Http\Message\ResponseInterface or rejected with an exception.

You can provide a custom handler to a client using the handler option of a client constructor. It is important to understand that several request options used by Guzzle require that specific middlewares wrap the handler used by the client. You can ensure that the handler you provide to a client uses the default middlewares by wrapping the handler in the GuzzleHttp\HandlerStack::create(callable $handler = null) static method.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Handler\CurlHandler;
  4. $handler = new CurlHandler();
  5. $stack = HandlerStack::create($handler); // Wrap w/ middleware
  6. $client = new Client(['handler' => $stack]);

The create method adds default handlers to the HandlerStack. When the HandlerStack is resolved, the handlers will execute in the following order:

  1. Sending request:
  1. http_errors - No op when sending a request. The response status code is checked in the response processing when returning a response promise up the stack.
  2. allow_redirects - No op when sending a request. Following redirects occurs when a response promise is being returned up the stack.
  3. cookies - Adds cookies to requests.
  4. prepare_body - The body of an HTTP request will be prepared (e.g., add default headers like Content-Length, Content-Type, etc.).
  5. <send request with handler>
  1. Processing response:
  1. prepare_body - no op on response processing.
  2. cookies - extracts response cookies into the cookie jar.
  3. allow_redirects - Follows redirects.
  4. http_errors - throws exceptions when the response status code >= 300.

When provided no $handler argument, GuzzleHttp\HandlerStack::create() will choose the most appropriate handler based on the extensions available on your system.

Important

The handler provided to a client determines how request options are applied and utilized for each request sent by a client. For example, if you do not have a cookie middleware associated with a client, then setting the cookies request option will have no effect on the request.

Middleware

Middleware augments the functionality of handlers by invoking them in the process of generating responses. Middleware is implemented as a higher order function that takes the following form.

  1. use Psr\Http\Message\RequestInterface;
  2. function my_middleware()
  3. {
  4. return function (callable $handler) {
  5. return function (RequestInterface $request, array $options) use ($handler) {
  6. return $handler($request, $options);
  7. };
  8. };
  9. }

Middleware functions return a function that accepts the next handler to invoke. This returned function then returns another function that acts as a composed handler— it accepts a request and options, and returns a promise that is fulfilled with a response. Your composed middleware can modify the request, add custom request options, and modify the promise returned by the downstream handler.

Here’s an example of adding a header to each request.

  1. use Psr\Http\Message\RequestInterface;
  2. function add_header($header, $value)
  3. {
  4. return function (callable $handler) use ($header, $value) {
  5. return function (
  6. RequestInterface $request,
  7. array $options
  8. ) use ($handler, $header, $value) {
  9. $request = $request->withHeader($header, $value);
  10. return $handler($request, $options);
  11. };
  12. };
  13. }

Once a middleware has been created, you can add it to a client by either wrapping the handler used by the client or by decorating a handler stack.

  1. use GuzzleHttp\HandlerStack;
  2. use GuzzleHttp\Handler\CurlHandler;
  3. use GuzzleHttp\Client;
  4. $stack = new HandlerStack();
  5. $stack->setHandler(new CurlHandler());
  6. $stack->push(add_header('X-Foo', 'bar'));
  7. $client = new Client(['handler' => $stack]);

Now when you send a request, the client will use a handler composed with your added middleware, adding a header to each request.

Here’s an example of creating a middleware that modifies the response of the downstream handler. This example adds a header to the response.

  1. use Psr\Http\Message\RequestInterface;
  2. use Psr\Http\Message\ResponseInterface;
  3. use GuzzleHttp\HandlerStack;
  4. use GuzzleHttp\Handler\CurlHandler;
  5. use GuzzleHttp\Client;
  6. function add_response_header($header, $value)
  7. {
  8. return function (callable $handler) use ($header, $value) {
  9. return function (
  10. RequestInterface $request,
  11. array $options
  12. ) use ($handler, $header, $value) {
  13. $promise = $handler($request, $options);
  14. return $promise->then(
  15. function (ResponseInterface $response) use ($header, $value) {
  16. return $response->withHeader($header, $value);
  17. }
  18. );
  19. };
  20. };
  21. }
  22. $stack = new HandlerStack();
  23. $stack->setHandler(new CurlHandler());
  24. $stack->push(add_response_header('X-Foo', 'bar'));
  25. $client = new Client(['handler' => $stack]);

Creating a middleware that modifies a request is made much simpler using the GuzzleHttp\Middleware::mapRequest() middleware. This middleware accepts a function that takes the request argument and returns the request to send.

  1. use Psr\Http\Message\RequestInterface;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Handler\CurlHandler;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Middleware;
  6. $stack = new HandlerStack();
  7. $stack->setHandler(new CurlHandler());
  8. $stack->push(Middleware::mapRequest(function (RequestInterface $request) {
  9. return $request->withHeader('X-Foo', 'bar');
  10. }));
  11. $client = new Client(['handler' => $stack]);

Modifying a response is also much simpler using the GuzzleHttp\Middleware::mapResponse() middleware.

  1. use Psr\Http\Message\ResponseInterface;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Handler\CurlHandler;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Middleware;
  6. $stack = new HandlerStack();
  7. $stack->setHandler(new CurlHandler());
  8. $stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
  9. return $response->withHeader('X-Foo', 'bar');
  10. }));
  11. $client = new Client(['handler' => $stack]);

HandlerStack

A handler stack represents a stack of middleware to apply to a base handler function. You can push middleware to the stack to add to the top of the stack, and unshift middleware onto the stack to add to the bottom of the stack. When the stack is resolved, the handler is pushed onto the stack. Each value is then popped off of the stack, wrapping the previous value popped off of the stack.

  1. use Psr\Http\Message\RequestInterface;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Middleware;
  4. use GuzzleHttp\Client;
  5. $stack = new HandlerStack();
  6. $stack->setHandler(\GuzzleHttp\choose_handler());
  7. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  8. echo 'A';
  9. return $r;
  10. });
  11. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  12. echo 'B';
  13. return $r;
  14. });
  15. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  16. echo 'C';
  17. return $r;
  18. });
  19. $client->request('GET', 'http://httpbin.org/');
  20. // echoes 'ABC';
  21. $stack->unshift(Middleware::mapRequest(function (RequestInterface $r) {
  22. echo '0';
  23. return $r;
  24. });
  25. $client = new Client(['handler' => $stack]);
  26. $client->request('GET', 'http://httpbin.org/');
  27. // echoes '0ABC';

You can give middleware a name, which allows you to add middleware before other named middleware, after other named middleware, or remove middleware by name.

  1. use Psr\Http\Message\RequestInterface;
  2. use GuzzleHttp\Middleware;
  3. // Add a middleware with a name
  4. $stack->push(Middleware::mapRequest(function (RequestInterface $r) {
  5. return $r->withHeader('X-Foo', 'Bar');
  6. }, 'add_foo');
  7. // Add a middleware before a named middleware (unshift before).
  8. $stack->before('add_foo', Middleware::mapRequest(function (RequestInterface $r) {
  9. return $r->withHeader('X-Baz', 'Qux');
  10. }, 'add_baz');
  11. // Add a middleware after a named middleware (pushed after).
  12. $stack->after('add_baz', Middleware::mapRequest(function (RequestInterface $r) {
  13. return $r->withHeader('X-Lorem', 'Ipsum');
  14. });
  15. // Remove a middleware by name
  16. $stack->remove('add_foo');

Creating a Handler

As stated earlier, a handler is a function accepts a Psr\Http\Message\RequestInterface and array of request options and returns a GuzzleHttp\Promise\PromiseInterface that is fulfilled with a Psr\Http\Message\ResponseInterface or rejected with an exception.

A handler is responsible for applying the following Request Options. These request options are a subset of request options called “transfer options”.