api-platform / core

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

[Laravel] Validation not working in JSON:API format #6745

Open cay89 opened 2 days ago

cay89 commented 2 days ago

API Platform version(s) affected: 4.0.5

Description
If I set the formats to jsonapi in the config, I encounter to the following problems:

1, When the prop attribute is required

#[ApiResource(operations: [new Post()], rules: ['prop' => 'required'])]
class Example
{
    public function __construct(private int $prop)
    {
    }

    public function getProp(): int
    {
        return $this->prop;
    }
}

Request:

{
  "data": {
    "type": "string",
    "attributes": {
      "prop": 1
    }
  }
}

Response:

422 Error: Unprocessable Entity

{
  "description": "validation.required"
}

Whatever the value of prop is, the response will always be the same. The problems are:

2, When the value of the prop attribute should be in a list

#[ApiResource(operations: [new Post()], rules: ['prop' => 'list:1,2])]
class Example
{
    public function __construct(private int $prop)
    {
    }

    public function getProp(): int
    {
        return $this->prop;
    }
}

Request:

{
  "data": {
    "type": "string",
    "attributes": {
      "prop": 100
    }
  }
}

Response:

201

{
  "data": {
    "id": "/api/.well-known/genid/abb28ed91b7dd4f27fa0",
    "type": "Example",
    "attributes": {
      "prop": 100
    }
  }
}

Whatever the value of prop is, the answer will always be the same. The problem is:

How to reproduce
1, Set the formats to jsonapi in the config/api-platform.php

return [
//...
'formats' => [
    'jsonapi' => ['application/vnd.api+json'],
],

'patch_formats' => [
    'jsonapi' => ['application/vnd.api+json'],
],

'docs_formats' => [
    'jsonapi' => ['application/vnd.api+json'],
    'html' => ['text/html'],
],

'error_formats' => [
    'jsonapi' => ['application/vnd.api+json'],
],
// ...
]

2, Create a simple DTO to test the cases explained above.

#[ApiResource(operations: [new Post()], rules: ['prop' => 'required'])]
class Example
{
    public function __construct(private int $prop)
    {
    }

    public function getProp(): int
    {
        return $this->prop;
    }
}

3, Test the endpoint using the OpenAPI documentation page.

soyuka commented 2 days ago

Thanks for the bug report, looking into that.

soyuka commented 1 day ago

First part: https://github.com/api-platform/core/pull/6755

I need to investigate the list:1,2 rule as it's not the same problem.

cay89 commented 1 day ago

First part: #6755

I need to investigate the list:1,2 rule as it's not the same problem.

Thanks! I see that maybe this will resolve #6725 too.