0

I need to write an API to check if a user name already exists in a database. I want my server (Struts Action class instance in tomcat server) to return true/false.

Its something like this

checkUserName?userName=john

I want to know what is the standard way to do this? Shall I return a JSON response with just one boolean value ... seems like a overkill.

Shall I do something like manually setting the HTTP header to 200 or 404 (for true/false), but that seems to violate the actual purpose of using the headers which I believe must only be used to indicate network failures etc.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Sainath S.R
  • 3,074
  • 9
  • 41
  • 72

1 Answers1

3

(Too long for a comment.)

I don't see any reason not to return a standard JSON response with something indicating whether or not the user name exists. That's what APIs do: there's nothing "overkill" about providing a response useful across clients.

To your second point: headers do a lot more than "indicate network problems". A 404 isn't a network problem, it means the requested resource doesn't exist. It is not appropriate in your case, because you're not requesting a resource: the resource is checkUserName, which does exist. If instead your request was /userByName/john a 404 would be appropriate if the user didn't exist. That's not an appropriate request in this case, because you don't want to return the user.

A 401 isn't a network problem, it's an authentication issue. A 302 isn't a network problem, it's a redirect. Etc. Using HTTP response codes is entirely appropriate, if they match your requests.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Is there some header for the true /false use case – Sainath S.R Apr 07 '16 at 13:08
  • @SainathS.R A general HTTP "true" or "false" makes no sense from a query, and there's no way it could be applied in a general way. A 302 (mis-implemented across most browsers) *might* make sense, but don't do that. As stated in the answer, IMO a 404 is inappropriate since you're hitting a search endpoint, not a resource. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes – Dave Newton Apr 07 '16 at 13:12
  • OK I'll go with the Json then – Sainath S.R Apr 07 '16 at 13:23