Search code examples
symfonysymfony4api-platform.com

API Platform error with not nullable field


I have a simple entity

 /**
 * @var string|null
 *
 * @ORM\Column(name="city", type="string", length=255, nullable=false)
 * @Assert\NotNull()
 */
private $city;

 ...

  /**
 * @param string|null $city
 * @return CustomerAddressList
 */
public function setCity(?string $city): CustomerAddressList
{
    $this->city = $city;
    return $this;
}

If I try to pass null to the field city the result is a runtime exception instead of a validation error:

{
  "@context": "/api/v2/contexts/Error",
  "@type": "hydra:Error",
  "hydra:title": "An error occurred",
  "hydra:description": "The type of the address attribute must be string, NULL given."
}

If I change nullable=false to true then everything works fine, but it's not an acceptable solution.

How can I fix it?


Solution

  • Found the solution.

    * @ApiResource(
    *     denormalizationContext={"disable_type_enforcement"=false}
    * )
    

    Adding the denormalizationContext with "disable_type_enforcement"=false disable the validation of the request using Doctrine annotations.

    {
        "@context": "/api/v2/contexts/ConstraintViolationList",
        "@type": "ConstraintViolationList",
        "hydra:title": "An error occurred",
        "hydra:description": "city: This value should be not null",
        "violations": [
        {
        "propertyPath": ".city",
        "message": "This value should be not null."
    },
    

    If it's necessary to enforce the field to be of a specific type then it's necessary to add the proper @Assert\Type(...) as prior Symfony 4.3