πŸ“‘Responses

Depending on how you sent your request (synchronous/asynchronous) you will either receive an instance of Response or a PromiseInterface.

Handling synchronous responses

By default, Saloon will return an instance of Saloon\Http\Response. This response class contains many helpful methods for interacting with your HTTP response. You can see a list of the available methods below.

<?php

$forge = new ForgeConnector('api-token');
$response = $forge->send(new GetServersRequest);

$body = $response->body();
$decodedBody = $response->json();

By default, Saloon will not throw an exception if a synchronous request fails. Refer to the handling failures section for handling errors.

Available Methods

Handling asynchronous responses

When using concurrent requests/pooling or sendAsync , Saloon will respond with a GuzzleHttp\Promise\PromiseInterface. The promise will contain a Response a class described above. When the request fails, Saloon will not use the then method but return an instance of RequestExceptionin the otherwise block.

<?php

use Saloon\Contracts\Response;

$forge = new ForgeConnector('api-token');
$promise = $forge->sendAsync(new GetServersRequest);

$promise
    ->then(function (Response $response) {
        // Handle successful response
    })
    ->otherwise(function (Exception $exception) {
        // Handle failed request
    });

Custom responses

Sometimes you may want to use your response class. This is useful if you want to add your methods or overwrite Saloon's response methods. Saloon allows you to overwrite the response at a connector level for all requests or at a per-request level for a granular response.

You may extend the Saloon\Http\Response class or provide your own implementation with the Saloon\Contracts\Response interface. You may use the HasResponseHelpers middleware when making your own implementation to save defining every method.

Using the response property

The simplest way of registering a custom response is to use the $response property on either the connector or request.

<?php

use Saloon\Http\Connector;

class ForgeConnector extends Connector
{
    // {...}
    
    protected ?string $response = CustomResponse::class;
}

Using the resolveResponseClass method

When you need a more advanced way to define a custom response, use the resolveResponseClass method on either the connector or request.

<?php

use Saloon\Http\Connector;

class ForgeConnector extends Connector
{
    // {...}
    
    public function resolveResponseClass(): string
    {
        return CustomResponse::class;
    }
}

Last updated