Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper route for checking resource existence in a RESTful API [closed]

What's the best/restful way to design an API endpoint for checking existence of resources?

For example there is a user database. While new user tries to sign up I want to check if email has been used on-the-fly.

My idea is: POST /user/exists and payload would be something like {"email": "[email protected]"}. The response would be either 200 OK or 409 Conflict.

Is this a proper way?

Thanks!

like image 656
x1a0 Avatar asked Jan 13 '14 09:01

x1a0


People also ask

What is route in REST API?

Routing is a functionally based tag or Uri template used by APIs to match the desired action or methods expected to be executed. There are two types or rather two different types of Routing being used during development.

Which HTTP method to check if resource exists?

Java Language HttpURLConnection Check if resource exists If you are just checking if a resource exists, it better to use a HEAD request than a GET. This avoids the overhead of transferring the resource. Note that the method only returns true if the response code is 200 .


2 Answers

HEAD is the most effecient for existence checks:

HEAD /users/{username} 

Request a user's path, and return a 200 if they exist, or a 404 if they don't.

Mind you, you probably don't want to be exposing endpoints that check email addresses. It opens a security and privacy hole. Usernames that are already publicly displayed around a site, like on reddit, could be ok.

like image 127
Baz Avatar answered Sep 28 '22 00:09

Baz


I believe the proper way to just check for existence is to use a HEAD verb for whatever resource you would normally get with a GET request.

I recently came across a situation where I wanted to check the existence of a potentially large video file on the server. I didn't want the server to try and start streaming the bytes to any client so I implemented a HEAD response that just returned the headers that the client would receive when doing a GET request for that video.

You can check out the W3 specification here or read this blog post about practical uses of the HEAD verb.

I think this is awesome because you don't have to think about how to form your route any differently from a normal RESTful route in order to check for the existence of any resource, Whether that's a file or a typical resource, like a user or something.

like image 31
arjabbar Avatar answered Sep 28 '22 00:09

arjabbar