Unique Constraint in a RESTFul architecture
Asked Answered
L

2

11

With 15 years of stateful client-server software development experience (and it's inherent problems) I'm still trying to grasp the concept of statelessness in a RestFul architecture.

Suppose I have a generic interface to post business objects to my REST service. For example User resources. My user resource should have a constraint on the uniqueness of his email address. My initial reaction would be to use the underlying database facilities to "garantuee" this. The second reaction would be to introduce some locking or transactional mechanism.

But my Restafarian collegue responds: 'No!' The client should check if the email for the new user is unique and you should just accept the fact that there is a small window of time in which a duplicate email address could be inserted. The client application should be able to handle this conflict.

This in turn goes against everything I have learned and doesn't feel natural at all. Please enlighten me...

Lighting answered 17/9, 2012 at 9:29 Comment(0)
A
21

I see no reason to not return the appropriate HTTP code: 409 Conflict. This can be returned upon getting errors from your database.

It is nice for usability reasons to check if the e-mail address is unique before sending the request as you can prompt the user (and disable submit) to correct the problem. In any case server side verification is still advised.

Anta answered 17/9, 2012 at 9:40 Comment(0)
L
3

This has nothing to do with protocol statelessness. Statelessness only says that the server shouldn't be the one saving session-related state (http://en.wikipedia.org/wiki/Stateless_protocol).

In your case, User resources are not session state - they are persistent resources stored on and exposed by the server. There is no reason wrt statelessness to force the client to do this check (by iteratively fetching and checking all User resources), and it makes more sense to have the server do it. Whether this check is done by the server as a part of POSTing a new User resource, or there exists a separate resource that enables this check -- it essentially makes no difference since the server is doing this check either way. If you use a separate resource to first check if it is OK to POST a new User, and then make a new request to actually do the POST -- then there is the possibility of duplicate e-mail addresses. In such cases, the expected behavior is that the server notifies the client that the POST request has failed (using an appropriate HTTP response code, just as it would for the first request by which the client checked that the e-mail is OK).

In short: the server does the "check", and the client should be able to handle situations in which the server notifies it that the check failed.

Lucas answered 17/9, 2012 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.