Guzzle Middleware to Handle External Validation Failures

James Bannister • July 10, 2021 • 4 minute read

laravel

In this post I want to show how we use Guzzle middleware with Guzzle and Laravel Http clients to catch 422 validation failures from external services and turn them into local validation failures. This approach can be used for catching other errors, and you'd just need to adjust it to cover your use case. I'll start with a little backstory which explains why we wrote this, but if you're just after the code then just scroll down.

At my day job we run a number of different projects/services to support the platform we provide. These projects/services are what we call "macroservices" or "microliths"; they are essentially focussed monoliths that handle a specific domain concern. For example, our Companies service. This service has its own database, frontend, backend, and API and handles all things to do with companies and what a company can offer on our platform. We have around 20 different services in our constellation, and these primarily communicate with each other via REST APIs.

Some of our projects are wrappers that tie together a number of services and provide a portal for a particular type of user on our platform. These may store their own data in a database, but are fairly pure in the sense that they defer to a lot of other services in the background to persist and fetch data. We tend to end up writing a form request in the portal that validates a user's submission, but the service that the portal then talks to via an API will also have validation rules on its endpoint.

The validation rules are usually in sync, but occasionally there are rules that you cannot support in a different service. For example, a unique constraint on an email or username, without access to the datasource, you couldn't write a validation rule for it. You could write a custom rule into the portal to check against the service locally, but this is just one such example that is somewhat simplified. So, from time to time, we have requests that will pass validation in the portal, but fail against the service due to one of these rules.

If you're running Guzzle or the Laravel Http client with http_errors enabled, a 422 failure from an HTTP call will cause an exception, and if not handled cause a 500 for your users. If you have http_errors disabled (which is the default with the Laravel Http client) then the data returned may not be in the format you expected (given you have a validation failure payload).

In the apps that are client/customer facing, we want to try and make any errors as user-friendly as possible, and a 422 failure from an upstream service could be turned into local validation errors and then displayed nicely to your users.

We can achieve this using Guzzle middleware, which you can use with both the Guzzle client and the Laravel Http client.

First, we'll create the middleware class called ProxyValidationErrors. This can live wherever you like, but I opted to put it in App\Http\Guzzle:

<?php

namespace App\Http\Guzzle;

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Psr\Http\Message\RequestInterface;

class ProxyValidationErrors
{
    public function __invoke($handler)
    {
        return function (RequestInterface $request, array $options) use (&$handler) {
            return $handler($request, $options)->then(function ($response) {
                if ($response->getStatusCode() === 422) {
                    throw new ValidationException(
                        tap(
                            Validator::make(request()->all(), []),
                            fn ($validator) => collect(
                                json_decode($response->getBody()->getContents(), true)['errors'] ?? []
                            )->each(fn ($message, $field) => $validator->errors()->add($field, $message))
                        )
                    );
                }

                return $response;
            });
        };
    }
}

When Guzzle gets a request/response, it runs through the middleware stack (exactly the same way Laravel does). This class is checking if the response status code is 422 and if so it throws a ValidationException with a Validator that has been hydrated with the upstream errors.

We can then configure a Guzzle or Laravel Http client to use this middleware. Again, put this where you like, but your AppServiceProvider is a great place if you aren't sure where to place it.

use App\Http\Guzzle\ProxyValidationErrors;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

// Guzzle Client
$this->app->bind(Client::class, function () {
    $stack = HandlerStack::create();
    $stack->push(new ProxyValidationErrors);

    return new Client([
        'handler' => $stack,
        //... any other guzzle options you like
    ]);
});

// Laravel Http Client
$this->app->bind(PendingRequest::class, function () {
    return Http::withMiddleware(new ProxyValidationErrors);
});

To use these, you would then use dependency injection in your class to pull in either the Guzzle or Laravel Http client:

use App\Http\Requests\YourFormRequest;
use GuzzleHttp\Client;
use Illuminate\Http\Client\PendingRequest;

class ExampleController
{
    private Client $guzzleClient;

    private PendingRequest $laravelClient;

    public function __construct(Client $guzzleClient, PendingRequest $laravelClient) 
    {
        $this->guzzleClient = $guzzleClient;
        $this->laravelClient = $laravelClient;
    }

    public function store(YourFormRequest $request)
    {
        // With Guzzle
        $this->guzzleClient->post('http://example.com', [
            'json' => $request->validated(),
        ]);

        // With Laravel Http client
        $this->laravelClient->post('http://example.com', $request->validated());

        //...
    }
}

Whilst we do our best to make sure we never have a mismatch of validation rules, and we have plans for further improvements to how we handle cross service communication, this has been a great strategy for more gracefully handling unexpected 422 validation failures.


I hope you found this useful. If you have any feedback, thoughts, or different approaches to this then I'd love to hear from you; I'm @jryd_13 on Twitter.

Thanks!