Skip to content

Input params ​

params() returns the inputs of the endpoint. ApiPresenter reads and validates all of them before handle() runs, and handle() gets the values keyed by name.

Open the diagram at full size

Param classes ​

ClassReads fromNotes
GetInputParamquery stringsupports types and setMulti()
PostInputParamform body, $_POSTsupports types and setMulti()
PutInputParamform-encoded body of any methodno type conversion, but a type is still checked: INTEGER rejects even "12", so use STRING or no type
CookieInputParamcookieno type conversion, but a type is still checked: INTEGER rejects even "12", so use STRING or no type
FileInputParamuploaded file, $_FILESsetMulti() for several files
RawInputParamthe whole request body as a stringsetMulti() throws
JsonInputParamthe whole request body, decoded as JSONneeds a JSON schema; setMulti() throws

The second constructor argument of the first two is the type, a case of the Tomaj\NetteApi\Validation\InputType enum or its string constant:

php
new GetInputParam('limit', InputType::Integer);
new GetInputParam('limit', InputType::INTEGER); // the string 'integer', works the same

$param->getParamType() returns where the param is read from as a Params\ParamType enum (getType() still returns the string).

Settings ​

All params share a fluent API:

MethodEffect
setRequired()null or '' answers Field is required.
setDefault($value)used when the input is missing
setAvailableValues([...])only these values pass, else Field contains not available value(s). Keys of an associative array are the values, the array values are labels for the console.
setMulti()expects an array, ?id[]=1&id[]=2; types and allowed values apply to every item
setDescription()shown in OpenAPI and the console
addExample($name, $value)shown in OpenAPI and prefilled in the console

Types ​

TypeConversion
INTEGER, DOUBLE, FLOATnumeric strings are converted
BOOLEAN1, true (any case) are true, everything else is false
STRINGkept as it is
ARRAYmust be an array

A value that is not a number becomes null

In 3.x ?limit=abc with INTEGER is not an error: the value is converted to null before validation, so an optional param passes and a required one answers Field is required. Always handle null in handle(). The params example tests this.

JSON body ​

JsonInputParam takes a JSON schema as a string and validates the decoded body against it:

php
<?php

declare(strict_types=1);

namespace App\Api;

use App\UserRepository;
use Tomaj\NetteApi\Handlers\BaseHandler;
use Tomaj\NetteApi\Output\JsonOutput;
use Tomaj\NetteApi\Params\JsonInputParam;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

final class UserCreateHandler extends BaseHandler
{
    public function __construct(private UserRepository $users)
    {
        parent::__construct();
    }

    public function summary(): string
    {
        return 'Create a user';
    }

    public function tags(): array
    {
        return ['users'];
    }

    public function params(): array
    {
        return [
            // the whole request body, validated against a JSON schema
            (new JsonInputParam('user', (string) file_get_contents(__DIR__ . '/schema/user-create.json')))
                ->setRequired()
                ->addExample('Alice', ['name' => 'Alice', 'email' => 'alice@example.com']),
        ];
    }

    public function handle(array $params): ResponseInterface
    {
        $user = $this->users->add($params['user']['name'], $params['user']['email']);
        return new JsonApiResponse(201, ['user' => $user]);
    }

    public function outputs(): array
    {
        return [
            new JsonOutput(201, (string) file_get_contents(__DIR__ . '/schema/user.json'), 'The new user'),
        ];
    }
}

Broken JSON answers 400 with the parser message, a missing required body answers missing data.

The 400 response ​

With error details on (see Error handling), the errors are listed per param:

json
{"status":"error","message":"wrong input","detail":{"status":["Field contains not available value(s)"]}}

With details off, the response has only status and message.

FAQ ​

How do I read a JSON body without a schema? ​

Use RawInputParam and decode it yourself, or pass a permissive schema such as {"type":"object"} to JsonInputParam.

Why is my integer param null instead of 400? ​

Non-numeric values become null in 3.x, see the warning above. Make the param required or check for null.

Can a param take several values? ​

Yes, setMulti(), then send name[]=a&name[]=b. See the params example.

Where do the examples I add show up? ​

In the OpenAPI document and as prefilled values in the web console.

Can authorization read the params? ​

Not the parsed values. authorized() takes no arguments; read the value from the HTTP request yourself, as QueryApiKeyAuthentication does. Params are read before authorization but only the error handler gets them, see ApiPresenter pipeline.

Released under the MIT License.