How Should I Handle REST API Validation for Resource Requests?

0
2
Asked By CuriousCoder538 On

Hey everyone! I have a couple of questions about validating REST API requests that I hope you can help me with.

1. When I send a POST, PUT, or PATCH request to a resource at "/resource/{resourceId}", should I validate the Request DTO first or check if the resource with that "{resourceId}" exists first?

2. In the case where I send a Request DTO and it contains errors, I add those to a list to return later. But what about other validation checks like ensuring a field is unique or that a foreign key exists? Should those be checked as well and included in the validation errors?

Thanks a bunch!

1 Answer

Answered By DevGuru123 On

For a POST request where you're creating a resource, start by validating the DTO without checking the database. Just go ahead and insert it. If there’s a problem, like a foreign key issue, you can catch that and turn it into a nice error response.

For PUT or PATCH requests, I'd suggest loading the resource first, then validate the DTO. Think of it like a diff, which combines the existing resource with the new data. That way, you can validate what's changed before hitting the database. If any database constraints fail, make sure to catch those too and return them as field errors.

TechNerd99 -

That makes sense, but I think it's also common to validate the DTO for PUT/PATCH first. Like checking if required fields are filled out correctly before doing anything else.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.