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!
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With