-->

Request validator : validate an IRI

2019-08-16 20:18发布

问题:

I'm currently working with api-plateform which has been a great tool so far. I'd like to add some validator before my datas are stored into my database.

Api-platform works with IRI instead of plain id (even if you can change this behavior). I was wondering what would be the best way to validate an IRI.

Let's say I receive for instance "api/users/1". I would like to make sure that this IRI is actually valid (i.e the id exists in the table "user").

I could create a custom validator rule which would either call that IRI and see if it returns a valid result or even split the string to get the id and the table and then make an sql query to check if it's not null.

But I think both solutions are not really ideal. Do you have any clue for me ?

Thank you very much !

回答1:

API Platform will automatically convert the IRI to an instance of the referenced entity during the deserialization process.

If an invalid IRI is provided (malformed, or not found), API Platform will automatically throw an error and return a 400 (Bad Request) HTTP status.

You can use the Symfony validator both on the root entity and on the related entity (the user) if you want to add more advanced validation constraints. See for instance the @Valid constraint.