Validation
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 SubscribeThere are a bunch of different ways for the users of our API to mess things up, like bad JSON or doing silly things like passing a negative number for the value field. This is dragon gold, not dragon debt!
Invalid JSON
This chapter is all about handling these bad things in a graceful way. Try the POST endpoint. Let's send some invalid JSON. Hit Execute. Awesome! A 400 error! That's what we want. 400 - or any status code that starts with 4 - means that the client - the user of the API - made a mistake. 400 specifically means "bad request".
In the response, the type is hydra:error and it says: An error occurred and Syntax Error. Oh, and this trace only shows in the debug environment: it won't be shown on production.
So this is pretty sweet! Invalid JSON is handled out-of-the-box.
Business Rules Validation Constraints
Let's try something different, like sending empty JSON. This gives us the dreaded 500 error. Boo. Internally, API platform creates a DragonTreasure object... but doesn't set any data on it. And then it explodes when it hits the database because some of the columns are null.
And, we expected this! We're missing validation. Adding validation to our API is exactly like adding validation anywhere in Symfony. For example, find the name property. We need name to be required. So, add the NotBlank constraint, and hit tab. Oh, but I'm going to go find the NotBlank use statement... and change this to Assert. That's optional... but it's the way the cool kids tend do it in Symfony. Now say 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 | |
| } |
Below, add one more: Length. Let's say that the name should be at least two characters, max 50 characters... and add a 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 | |
| } |
How Errors Look in the Response
Good start! Let's try it again. Take that same empty JSON, hit Execute, and yes! A 422 response! This is a really common response code that usually means there was a validation error. And behold! The @type is ConstraintViolationList. This is a special JSON-LD type added by API Platform. Earlier, we saw this documented in the JSON-LD documentation.
Watch: go to /api/docs.jsonld and search for a ConstraintViolation. There it is! API Platform adds two classes - ConstraintViolation and ConstraintViolationList to describe how validation errors will look. A ConstraintViolationList is basically just a collection of ConstraintViolations... and then it describes what the ConstraintViolation properties are.
We can see these over here: we have a violations property with propertyPath and then the message below.
Adding More Constraints
Ok! Let's sneak in a few more constraints. Add NotBlank above description... and GreaterThanOrEqual to 0 above value to avoid negatives. Finally, for coolFactor use GreaterThanOrEqual to 0 and also LessThanOrEqual to 10. So something between 0 and 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 | |
| } |
And while we're here, we don't need to do this, but I'm going to initialize $value to 0 and $coolFactor to 0. This makes both of those not required in the API: if the user doesn't send them, they'll default to 0:
| // ... 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 | |
| } |
Ok, go back and try that same endpoint. Look at that beautiful validation! Also try setting coolFactor to 11. Yup! No treasure is that cool... well, unless it's a giant plate of nachos.
Passing Bad Types
Ok, there's one last way that a user can send bad stuff: by passing the wrong type. So coolFactor: 11 will fail our validation rules. But what if we pass a string instead? Yikes! Hit Execute. Okay: a 400 status code, that's good. Though, it's not a validation error, it has a different type. But it does tell the user what happened:
the type of the
coolFactorattribute must beint,stringgiven.
Good enough! This is thanks to the setCoolFactor() method. The system sees the int type and so it rejects the string with this error.
So the only thing that we need to worry about in our app is writing good code that properly uses type and adding validation constraints: the safety net that catches business rule violations... like value should be greater than 0 or description is required. API Platform handles the rest.
Next: our API only has one resource: DragonTreasure. Let's add a second resource - a User resource - so that we can link which user owns which treasure in the 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!