Rest – Performing a username lookup before registering a User while conforming to REST philosophy

rest

I have a REST Service based on Spring MVC. JSON is the only interchange format for any client to talk to this service.

I'm working on implementing a user registration workflow. So I have created an endpoint (/register, payload=User object in JSON) that accepts the User entity and does it's thing. So I'm transferring the state of an object which makes me content about adhering to the REST philosophy (I think).

My question is: Before I can register a user, I need to check if ther username is already used up. So I can create a new endpoint /register/username/
But this idea sounds bad and not RESTful at all as I'm using the endpoint to perform an action, not transfer of state. And this sounds like I'm invoking a method to perform an action (remote RPC). How can I re think this in terms of REST?

Best Answer

I'm using the endpoint to perform an action, not transfer of state.

Actually, you are transferring state. The client is sending the proposed new user entity to the server. The server has its own rules to enforce, however, so it must refuse to create a user if their unique identifier already exists.

There is already an HTTP error code for that. As @tom pointed out, the 409 Conflict response code is acceptable for that. It basically means What you asked me to do is perfectly legal in from your standpoint. I am simply unable to fulfill your request because it is in conflict with something outside of your control versus some of the other response codes which focus on inappropriate client requests.

As far as your concern about using REST to perform an action in this case, I don't agree, but I am glad you are thinking about that. I have seen developers create "REST services" named things like GET /whatever/updateWidget, which is clearly not a RESTful way of thinking.

You are performing an action only in the sense that you are creating a new resource. But that resource is based on the state you transferred. You have to create it somehow.

As long as you return a meaningful error code like 409, I do not see any problems with your approach whatsoever.

Related Topic