Validación
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeLos usuarios de nuestra API pueden estropear las cosas de muchas maneras, por ejemplo con un JSON incorrecto o haciendo tonterías como introducir un número negativo en el campo value. ¡Esto es oro de dragón, no deuda de dragón!
JSON no válido
Este capítulo trata sobre cómo manejar estas cosas malas con elegancia. Prueba con la ruta POST. Enviemos algo de JSON no válido. Pulsa Ejecutar. ¡Impresionante! ¡Un error 400! Eso es lo que queremos. 400 -o cualquier código de estado que empiece por 4- significa que el cliente -el usuario de la API- ha cometido un error. en concreto, 400 significa "petición errónea".
En la respuesta, el tipo es hydra:error y dice: An error occurred y Syntax Error. Ah, y este trace sólo se muestra en el entorno de depuración: no se mostrará en producción.
¡Así que esto es muy bonito! El JSON no válido se gestiona de forma automática.
Restricciones de validación de reglas de negocio
Probemos algo diferente, como enviar JSON vacío. Esto nos da el temido error 500. Boo. Internamente, la API Platform crea un objeto DragonTreasure... pero no establece ningún dato en él. Y luego explota cuando llega a la base de datos porque algunas de las columnas son null.
Y, ¡nos lo esperábamos! Nos falta la validación. Añadir validación a nuestra API es exactamente igual que añadir validación en cualquier parte de Symfony. Por ejemplo, busca la propiedadname. Necesitamos que name sea obligatoria. Así que añade la restricción NotBlank, y pulsa tabulador. Oh, pero voy a buscar la declaración NotBlank use ... y cambiarla por Assert. Eso es opcional... pero es la forma en que los chicos guays suelen hacerlo en Symfony. Ahora di Assert\NotBlank:
| // ... lines 1 - 19 | |
| use Symfony\Component\Validator\Constraints as Assert; | |
| // ... lines 21 - 51 | |
| class DragonTreasure | |
| { | |
| // ... lines 54 - 61 | |
| // ... line 63 | |
| private ?string $name = null; | |
| // ... lines 65 - 188 | |
| } |
A continuación, añade una más: Length. Digamos que el nombre debe tener al menos dos caracteres, max 50 caracteres... y añade un maxMessage:Describe your loot in 50 chars or less:
| // ... lines 1 - 19 | |
| use Symfony\Component\Validator\Constraints as Assert; | |
| // ... lines 21 - 51 | |
| class DragonTreasure | |
| { | |
| // ... lines 54 - 61 | |
| (min: 2, max: 50, maxMessage: 'Describe your loot in 50 chars or less') | |
| private ?string $name = null; | |
| // ... lines 65 - 188 | |
| } |
Cómo se ven los errores en la respuesta
¡Buen comienzo! Inténtalo de nuevo. Coge ese mismo JSON vacío, pulsa Ejecutar, y ¡sí! ¡Una respuesta 422! Se trata de un código de respuesta muy común que suele significar que se ha producido un error de validación. Y ¡he aquí! El @type es ConstraintViolationList. Se trata de un tipo especial de JSON-LD añadido por API Platform. Anteriormente, lo vimos documentado en la documentación de JSON-LD.
Observa: ve a /api/docs.jsonld y busca un ConstraintViolation. ¡Ahí está! API Platform añade dos clases: ConstraintViolation yConstraintViolationList para describir el aspecto que tendrán los errores de validación. UnConstraintViolationList es básicamente una colección de ConstraintViolations... y luego describe cuáles son las propiedades de ConstraintViolation.
Podemos verlas aquí: tenemos una propiedad violations con propertyPathy luego la message debajo.
Añadir más restricciones
¡Vale! Vamos a añadir unas cuantas restricciones más. Añade NotBlank por encima de description... y GreaterThanOrEqual a 0 por encima de value para evitar los negativos. Por último, paracoolFactor utiliza GreaterThanOrEqual a 0 y también LessThanOrEqual a 10. Así que algo entre 0 y 10:
| // ... lines 1 - 51 | |
| class DragonTreasure | |
| { | |
| // ... lines 54 - 68 | |
| private ?string $description = null; | |
| // ... lines 71 - 77 | |
| (0) | |
| private ?int $value = null; | |
| // ... lines 80 - 82 | |
| (0) | |
| (10) | |
| private ?int $coolFactor = null; | |
| // ... lines 86 - 192 | |
| } |
Y ya que estamos aquí, no necesitamos hacer esto, pero voy a inicializar$value a 0 y $coolFactor a 0. Esto hace que ambos no sean necesarios en la API: si el usuario no los envía, serán 0 por defecto:
| // ... lines 1 - 51 | |
| class DragonTreasure | |
| { | |
| // ... lines 54 - 68 | |
| private ?string $description = null; | |
| // ... lines 71 - 77 | |
| (0) | |
| private ?int $value = 0; | |
| // ... lines 80 - 82 | |
| (0) | |
| (10) | |
| private ?int $coolFactor = 0; | |
| // ... lines 86 - 192 | |
| } |
Vale, vuelve a probar esa misma ruta. ¡Mira qué validación más bonita! Prueba también a poner coolFactor en 11. ¡Sí! Ningún tesoro mola tanto... bueno, a menos que sea un plato gigante de nachos.
Pasar tipos malos
Vale, hay una última forma de que un usuario envíe cosas malas: pasando un tipo incorrecto. Así que coolFactor: 11 fallará nuestras reglas de validación. Pero, ¿y si en su lugar pasamos un string? ¡Qué asco! Pulsa Ejecutar. Vale: un código de estado 400, eso es bueno. Aunque, no es un error de validación, tiene un tipo diferente. Pero indica al usuario lo que ha ocurrido:
el tipo del atributo
coolFactordebe serint,stringdado.
¡Suficientemente bueno! Esto es gracias al método setCoolFactor(). El sistema ve el tipo int y por eso rechaza la cadena con este error.
Así que de lo único que tenemos que preocuparnos en nuestra aplicación es de escribir un buen código que utilice correctamente type y de añadir restricciones de validación: la red de seguridad que atrapa las violaciones de las reglas de negocio... como que value debe ser mayor que 0 o que descriptiones obligatorio. API Platform se encarga del resto.
A continuación: nuestra API sólo tiene un recurso: DragonTreasure. Añadimos un segundo recurso -un recurso User - para que podamos vincular qué usuario posee qué tesoro en la API.
6 Comments
hi, regarding coolFactor, is there any way we can validate that the type must be numeric so the response will have status 422 with the error message instead of 400?
I tried the Type validation with numeric type but it doesn't work
Yo @Huy!
I think I understand :). In this case,
coolFactoris private property, so we're setting it via thesetCoolFactor()method. Because it has aninttype-hint -setCoolFactor(int $coolFactor)- if the user sendsapplefor this, it will fail during denormalization (i.e. it will fail to even SET the value). This gives us the 400 error. It never even GETS to the validation step.If you want to, instead, enforce this via validation, you need to allow the
coolFactorproperty to be set to a string... which you CAN do, but it's kind of a bummer to allow such a weird value to even get set into your entity (even if you will validate it). So, you would need to:A) Remove the
?intproperty type from thecoolFactorpropertyB) Remove the
inttype from thesetCoolFactor()methodThat will allow the serializer to set the value... and THEN validation will happen. Let me know if this helps!
Cheers!
Hi @weaverryan, thank you, it works but when I pass the correct coolFactor in the request body, it returns 400 error like below
The request:
The response:
Then I try to validate the $isPublished with the annotation #[Assert\Type('bool')] to make sure the isPublished must be boolean type (not number, string...). then I send the request with $isPublished = 123, although I tried the approach you suggested above like removing the ?bool int property type and bool type from setIsPublished, the response status is still 400 instead of 422.
Sample request:
POST api/treasures
Response 400:
This is my DragonTreasure entity
Could you suggest any ways to resolve this issue?
Hey @Huy!
Hmm. I have a feeling this is being caused by Doctrine. So when deserialization happens, it uses Symfony's property-info component to get the "type" of a property - e.g.
coolFactorin this case. To get the type, it looks for a true PHP type on the property, a type on the argument insetCoolFactor()and it even looks at your PHPDoc - e.g. for an@varabove the property. If It finds a type & the type send by the user doesn't match, it'll throw that 400 error.However, you have NONE of that. But I still think that SOMETHING is "guessing" the type of your field. The property-info component also gets metadata from Doctrine. And, because you don't have a
typein your column, this is a string field. And so, this might be telling the property info system that this is astringfield. Still, it's a bit annoying, since if you send the integer40, PHP can very easily cast that to the string'40'.Anyway, the only way that I know of around this problem - which might actually be perfect for you - is to set
ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => falsein your context. So you could add adenormalizationContextoption to your#[ApiResource]and set that there. Just be aware that the serializer will now ALWAYS set the value onto your properties, even if it's something crazy (e.g. the user could, I think, even send an array to thecoolFactorproperty). If your code explodes when that is set (before validation) that would trigger a 500 error.Anyway, with this option, you could actually, I think, re-add your property types, etc.
Cheers!
So, I'm a bit stumped as to WHY the serializer still thinks that
coolFactorHi @weaverryan
I followed your suggestion but it still didn't work. When I pass the coolFactor as an integer, the response status still is 400.
Moreover, I also can not find the ObjectNormalizer class, it seems the class AbstractObjectNormalizer instead
The DragonTreasure entity:
The sample request payload:
PATCH api/treasures/:id
Hey @Huy!
Hmm. First, yea,
AbstractObjectNormalizeris correct -ObjectNormalizershould work too (it's a sub-class), but the constant is onAbstractObjectNormalizer- so that's better anyway.So you're still getting a response that looks like this?
I don't know if it's related, but I did misspeak in my previous message. You will still need to NOT have an argument type on
setCoolFactor()and you still need to NOT have a property type on the$coolFactorproperty. This is because we DO need to allow the property to be set with astringtype (for example) so that we can THEN run validation on that.Cheers!
"Houston: no signs of life"
Start the conversation!