How should I design a RESTful URL to validate an o

2019-04-21 20:02发布

Without moving away from the RESTful paradigm, how could you model object validation in a RESTful way? Best to explain the theoretical use case I've come up with...

Imagine you have a system with a very thin web layer making calls to back-end RESTful services. Say a user visited a registration form and submitted it, the web layer would send the unvalidated data straight to a back-end service and, if the service responds with validation errors in JSON format, these can be sent back to the user as HTML.

However, imagine we want to have AJAX behaviour on the form. For example, the user enters their email address and we want to validate using AJAX, sending an error to the user if their email address is already registered.

Would it make sense to implement a single call to validate just the email address, or could the whole object be sent and validated in a back-end service? If the latter, what URL could you use to only validate an object, rather than actually create it?

标签: rest
2条回答
Anthone
2楼-- · 2019-04-21 21:00

In the past I have used the notion of a sandbox sub-resource to do what you are suggesting,

http://example.com/customer/23/sandbox

This allows me to POST deltas and have the changes applied and validated but not actually committed. This works quite well for the traditional "save/cancel" type dialogs.

However, I found dealing with those deltas to be a real pain, so I developed a different media type that recorded a sequence of events on the client and then posted that document to the sandbox resource. By replaying the sequence of events I could update and validate the server side resource in a simpler fashion.

Later on I realized that I really didn't need the distinct "sandbox" resource and now I just post the "sequence of events" document directly to the resource it is affecting. I have some data in the document itself that determines whether the changes are going to be permanent or just transient. It just depends if the user has pressed the save button yet or not.

查看更多
欢心
3楼-- · 2019-04-21 21:02

Validating a single form field can improve user experience while the user is filling the form, but when the form is submitted, I would validate the whole object, because it's less error prone. The URL can be simply https://mysite.com/users/emailvalidator for validating the e-mail only (a single field), and the form could be POSTed to https://mysite.com/users (the whole object). In the former case, the URL tells clearly that the resource you want to use is an object which is able to validate an e-mail.

查看更多
登录 后发表回答