sajad torkamani

In a nutshell

API Platform provides a bridge with the Symfony Validator component so adding its validation constraints / custom constraint to your entities is enough to validate user-submitted data.

How to apply validation

Add validation constraints

Add the Symfony Validator namespace:

use Symfony\Component\Validator\Constraints as Assert;

And then add whatever constraint you need to whatever property:

#[ORM\Entity(repositoryClass: NoteRepository::class)]
#[ApiResource]
class Note
{
    #[Assert\NotBlank]
    #[ORM\Column(type: 'string', length: 255)]
    private string $title;

   // blah blah blah
}

Test validation works as expected

Make an invalid request:

curl -X 'POST' \
  'https://localhost:8000/api/notes' \
  -H 'accept: application/ld+json' \
  -H 'Content-Type: application/ld+json' \
  -d '{
  "title": ""
}'

And you should get a 422 response that looks something like:

{
  "@context": "/api/contexts/ConstraintViolationList",
  "@type": "ConstraintViolationList",
  "hydra:title": "An error occurred",
  "hydra:description": "title: This value should not be blank.",
  "violations": [
    {
      "propertyPath": "title",
      "message": "This value should not be blank.",
      "code": "c1051bb4-d103-4f74-8988-acbcafc7fdc3"
    }
  ]
}

Sources