api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.43k stars 864 forks source link

Validation doesn't work proppperly with strict types #6392

Closed mantaszv closed 4 months ago

mantaszv commented 4 months ago

API Platform version(s) affected: 3.2 I saw multiple same issue reports, but they were closed by not fixing.

#[ApiResource()]
class UserApi
{
    #[Assert\Type('string')]
    public ?string $name = null;
}

if I remove property type '?string' it works fine.

if I pass integer in name: {'name':1}

Expected status 422

{\n
    "@id": "/api/validation_errors/ba785a8c-82cb-4283-967c-3cf342181b40",\n
    "@type": "ConstraintViolationList",\n
    "status": 422,\n
    "violations": [\n
        {\n
            "propertyPath": "name",\n
            "message": "This value should be of type string.",\n
            "code": "ba785a8c-82cb-4283-967c-3cf342181b40"\n
        }\n
    ],\n
    "detail": "name: This value should be of type string.",\n
    "hydra:title": "An error occurred",\n
    "hydra:description": "name: This value should be of type string.",\n
    "type": "/validation_errors/ba785a8c-82cb-4283-967c-3cf342181b40",\n
    "title": "An error occurred"\n
}

Actual status 400

{\n
    "@id": "/api/errors/400",\n
    "@type": "hydra:Error",\n
    "title": "An error occurred",\n
    "detail": "The type of the \"name\" attribute must be \"string\", \"integer\" given.",\n
    "status": 400,\n
    "type": "/errors/400",\n
    "trace": [\n
        {\n
            "file": "/var/www/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",\n
            "line": 528,\n
            "function": "createForUnexpectedDataType",\n
            "class": "Symfony\\Component\\Serializer\\Exception\\NotNormalizableValueException",\n
            "type": "::"\n
        },\n
        {\n
            "file": "/var/www/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",\n
            "line": 1013,\n
            "function": "validateType",\n
            "class": "ApiPlatform\\Serializer\\AbstractItemNormalizer",\n
            "type": "->"\n
        },\n
...
soyuka commented 4 months ago

This is expected as the serializer throws early solution here https://api-platform.com/docs/core/validation/#collecting-denormalization-errors