Skip to content

Example: typed input ​

Four handlers extend TypedHandler. The DTO on handleDto() is the request contract: #[Query], #[Path], #[Header], #[Body] and #[File]. The same order endpoint accepts JSON and a URL-encoded form. See Typed input.

Since 4.0.0

Typed handlers, path and header parameters and #[Consumes] are new in 4.0.0.

RequestStatusWhat it shows
GET /api/v1/users/list200page defaults to 1, status is null
GET /api/v1/users/list?page=2&status=active200integer and backed enum
GET /api/v1/users/list?page=1a4001a is not an integer
GET /api/v1/users/42/detail with X-Request-Id200path id and header
POST /api/v1/orders JSON201nested DTO and list<ItemInput>
POST /api/v1/orders form201the same DTO, bracket names
POST /api/v1/orders invalid body400items[1].quantity
POST /api/v1/orders text/csv415content type outside the default pair
POST /api/v1/orders postal code 81101 plus a newline400$ in the pattern ends the string
POST /api/v1/avatar multipart201FileUpload
GET /api/v1/openapi200path and header parameters, a multipart body

A query DTO ​

php
<?php

declare(strict_types=1);

namespace App\Api\Input;

use Tomaj\NetteApi\Input\Query;
use Tomaj\NetteApi\Validation\Range;

final readonly class ListUsersInput
{
    public function __construct(
        #[Query(description: 'Page number')]
        #[Range(min: 1)]
        public int $page = 1,
        #[Query]
        public ?UserStatus $status = null,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Api;

use App\Api\Input\ListUsersInput;
use Tomaj\NetteApi\Attribute\Get;
use Tomaj\NetteApi\Handlers\TypedHandler;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

#[Get(1, 'users', 'list')]
final class ListUsersHandler extends TypedHandler
{
    public function handleDto(ListUsersInput $input): ResponseInterface
    {
        return new JsonApiResponse(200, [
            'page' => $input->page,
            'status' => $input->status?->value,
        ]);
    }
}

A path and header DTO ​

php
<?php

declare(strict_types=1);

namespace App\Api\Input;

use Tomaj\NetteApi\Input\Header;
use Tomaj\NetteApi\Input\Path;
use Tomaj\NetteApi\Validation\Range;

final readonly class UserDetailInput
{
    public function __construct(
        #[Path]
        #[Range(min: 1)]
        public int $id,
        #[Header('X-Request-Id')]
        public ?string $requestId = null,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Api;

use App\Api\Input\UserDetailInput;
use Tomaj\NetteApi\Attribute\Get;
use Tomaj\NetteApi\Handlers\TypedHandler;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

#[Get(1, 'users', '{id}/detail')]
final class UserDetailHandler extends TypedHandler
{
    public function handleDto(UserDetailInput $input): ResponseInterface
    {
        return new JsonApiResponse(200, [
            'id' => $input->id,
            'requestId' => $input->requestId,
        ]);
    }
}

A nested body DTO ​

CreateOrderInput nests an AddressInput and a list<ItemInput>; the same classes read a JSON body and a URL-encoded form with bracket names.

php
<?php

declare(strict_types=1);

namespace App\Api\Input;

use Tomaj\NetteApi\Input\Body;
use Tomaj\NetteApi\Validation\Email;
use Tomaj\NetteApi\Validation\Length;

final readonly class CreateOrderInput
{
    /** @param list<ItemInput> $items */
    public function __construct(
        #[Body]
        #[Email]
        public string $customerEmail,
        #[Body]
        public AddressInput $address,
        #[Body]
        #[Length(min: 1, max: 50)]
        public array $items,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Api\Input;

use Tomaj\NetteApi\Input\Body;
use Tomaj\NetteApi\Validation\Length;
use Tomaj\NetteApi\Validation\Pattern;

final readonly class AddressInput
{
    public function __construct(
        #[Body]
        #[Length(min: 1, max: 120)]
        public string $street,
        #[Body]
        #[Pattern('/^[0-9]{5}$/')]
        public string $postalCode,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Api\Input;

use Tomaj\NetteApi\Input\Body;
use Tomaj\NetteApi\Validation\Range;

final readonly class ItemInput
{
    public function __construct(
        #[Body]
        public string $sku,
        #[Body]
        #[Range(min: 1)]
        public int $quantity,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Api;

use App\Api\Input\CreateOrderInput;
use Tomaj\NetteApi\Attribute\Post;
use Tomaj\NetteApi\Handlers\TypedHandler;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

#[Post(1, 'orders')]
final class CreateOrderHandler extends TypedHandler
{
    public function handleDto(CreateOrderInput $input): ResponseInterface
    {
        return new JsonApiResponse(201, [
            'email' => $input->customerEmail,
            'street' => $input->address->street,
            'items' => count($input->items),
            'quantity' => $input->items[0]->quantity,
        ]);
    }
}

A file upload ​

php
<?php

declare(strict_types=1);

namespace App\Api\Input;

use Tomaj\NetteApi\Input\Body;
use Tomaj\NetteApi\Input\File;
use Tomaj\NetteApi\Input\FileUpload;
use Tomaj\NetteApi\Validation\Length;

final readonly class AvatarInput
{
    public function __construct(
        #[Body]
        #[Length(min: 1, max: 80)]
        public string $displayName,
        #[File(description: 'PNG or JPEG image')]
        public FileUpload $avatar,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Api;

use App\Api\Input\AvatarInput;
use Tomaj\NetteApi\Attribute\Post;
use Tomaj\NetteApi\Handlers\TypedHandler;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

#[Post(1, 'avatar')]
final class AvatarUploadHandler extends TypedHandler
{
    public function handleDto(AvatarInput $input): ResponseInterface
    {
        $avatar = $input->avatar;
        if ($avatar->error !== UPLOAD_ERR_OK) {
            return new JsonApiResponse(400, ['status' => 'error', 'message' => 'upload failed']);
        }

        return new JsonApiResponse(201, [
            'name' => $input->displayName,
            'file' => $avatar->originalName,
            'size' => $avatar->size,
        ]);
    }
}

Registration ​

The path endpoint is #[Get(1, 'users', '{id}/detail')]. The route is the usual one, with an optional third segment:

php
<?php

declare(strict_types=1);

namespace App;

use Nette\Application\Routers\RouteList;

final class RouterFactory
{
    public static function create(): RouteList
    {
        $router = new RouteList();
        // {id} in users/{id}/detail is one more segment, captured by <params>
        $router->addRoute('/api/v<version>/<package>[/<apiAction>][/<params>]', 'Api:Api:default');
        return $router;
    }
}
neon
extensions:
	api: Tomaj\NetteApi\DI\NetteApiExtension

services:
	router: App\RouterFactory::create
	apiLink: Tomaj\NetteApi\Link\ApiLink

api:
	outputConfigurator: Tomaj\NetteApi\Output\Configurator\EnvConfigurator('APP_ENV', 'production')

	discovery:
		paths: [%appDir%/Api]
		namespace: App\Api

	endpoints:
		- {method: GET, version: 1, package: openapi, handler: Tomaj\NetteApi\Handlers\OpenApiHandler, authorization: false}

Released under the MIT License.