Response format

Response format

The result schema in the documentation is built automatically from the type the method returns. A separate attribute is needed only when the type cannot be inferred from the signature.

Scalar types

For string, int, float, bool, nullable and union types, the schema is taken from the native return type.

public function ping(): string

Arrays: type from PHPDoc

For array, the exact type is specified in @return. It takes precedence over the native type.

/**
 * @return array<string, int>
 */
public function stats(): array

DTO

If a method returns a class (or an array of a class in @return), that class becomes the result format: a DTO schema with all its properties appears in OpenRPC, and the object is serialized into the response.

final class UserDto
{
    public function __construct(
        public int $id,
        public string $email,
        public ?string $name = null,
    ) {}
}

public function get(int $id): UserDto

/**
 * @return UserDto[]
 */
public function list(): array

Request

{"jsonrpc": "2.0", "id": 1, "method": "User.get", "params": {"id": 5}}

Response

{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {"id": 5, "email": "user@example.com", "name": null}
}

DTO property types are taken from native types and PHPDoc (@var, constructor @param for promoted properties). Properties that have a converter (enum, date, UUID, Doctrine entity) are converted to scalars in the response.

#[RPC\DTO]

When a method returns array or object but the format is known, specify it with an attribute on the method:

use Ufo\RpcObject\RPC;

#[RPC\DTO(UserDto::class)]
public function getRaw(int $id): array

#[RPC\DTO(UserDto::class, collection: true)]
public function listRaw(): array

Signature: DTO(string $dtoFQCN, bool $collection = false, array $context = []). For a collection on a method, use collection: true: #[RPC\DTOCollection] on a method is currently not read (see Open issues). The attribute also works on DTO properties to set the type of nested objects and collections.

Migrating from older versions

#[RPC\Response] is not read since version 7.6, and #[RPC\ResultAsDTO] has been replaced by #[RPC\DTO]. The description for older versions is available in the version selector at the top of the page.