Preskočiť na obsah

Príklad: typovaný vstup ​

Štyri handlery dedia z TypedHandler. DTO na handleDto() je kontrakt požiadavky: #[Query], #[Path], #[Header], #[Body] a #[File]. Rovnaký endpoint objednávky prijme JSON aj formulár. Pozrite Typovaný vstup.

Od verzie 4.0.0

Typované handlery, path a header parametre a #[Consumes] sú nové v 4.0.0.

PožiadavkaStavČo ukazuje
GET /api/v1/users/list200page má predvolenú hodnotu 1, status je null
GET /api/v1/users/list?page=2&status=active200celé číslo a backed enum
GET /api/v1/users/list?page=1a4001a nie je celé číslo
GET /api/v1/users/42/detail s X-Request-Id200id z cesty a hlavička
POST /api/v1/orders JSON201vnorené DTO a list<ItemInput>
POST /api/v1/orders formulár201to isté DTO, zátvorkové mená
POST /api/v1/orders neplatné telo400items[1].quantity
POST /api/v1/orders text/csv415typ obsahu mimo predvolenej dvojice
POST /api/v1/orders PSČ 81101 a nový riadok400$ vo vzore končí reťazec
POST /api/v1/avatar multipart201FileUpload
GET /api/v1/openapi200parametre cesty a hlavičky, multipart telo

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,
        ]);
    }
}

DTO s cestou a hlavičkou ​

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,
        ]);
    }
}

Vnorené DTO tela ​

CreateOrderInput obsahuje vnorený AddressInput a list<ItemInput>; tie isté triedy čítajú JSON telo aj URL-enkódovaný formulár s názvami so zátvorkami.

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,
        ]);
    }
}

Nahrávanie súboru ​

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,
        ]);
    }
}

Registrácia ​

Endpoint s cestou je #[Get(1, 'users', '{id}/detail')]. Routa je obvyklá, s voliteľným tretím segmentom:

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}

Vydané pod licenciou MIT.