REST Check if resource exists, how to handle on server side?

how to handle multiple request in rest api
rest get if exists
idempotent rest
rest exists endpoint
http methods
idempotent in java
http head
rest head

how to handle resource checking on server side? For example, my api looks like:

/books/{id}

After googling i found, that i should use HEAD method to check, if resource exists. https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

I know, that i can use GET endpoint and use HEAD method to fetch information about resource and server does not return body in this case.

But what should i do on server side? I have two options.

  1. One endpoint marked as GET. I this endpoint i can use GET method to fetch data and HEAD to check if resource is available.

  2. Two endpoints. One marked as GET, second as HEAD.

Why i'm considering second solution? Let's assume, that GET request fetch some data from database and process them in some way which takes some time, eg. 10 ms

But what i actually need is only to check if data exists in database. So i can run query like

select count(*) from BOOK where id = :id

and immediately return status 200 if result of query is equal to 1. In this case i don't need to process data so i get a faster response time.

But... resource in REST is a object which is transmitted via HTTP, so maybe i should do processing data but not return them when i use HEAD method?

Thanks in advance for your answer!

You could simply delegate the HEAD handler to the existing GET handler and return the status code and headers only (ignoring the response payload).

That's what some frameworks such as Spring MVC and JAX-RS do.


See the following quote from the Spring MVC documentation:

@GetMapping — and also @RequestMapping(method=HttpMethod.GET), are implicitly mapped to and also support HTTP HEAD. An HTTP HEAD request is processed as if it were HTTP GET except but instead of writing the body, the number of bytes are counted and the " Content-Length header set.

[...]

@RequestMapping method can be explicitly mapped to HTTP HEAD and HTTP OPTIONS, but that is not necessary in the common case.

And see the following quote from the JAX-RS documentation:

HEAD and OPTIONS requests receive additional automated support. On receipt of a HEAD request an implementation MUST either:

  1. Call a method annotated with a request method designator for HEAD or, if none present,
  2. Call a method annotated with a request method designator for GET and discard any returned entity.

Note that option 2 may result in reduced performance where entity creation is significant.


Note: Don't use the old RFC 2616 as reference anymore. It was obsoleted by a new set of RFCs: 7230-7235. For the semantics of the HTTP protocol, refer to the RFC 7231.

REST API Design: Include functionality to see if resource(s) exist in , If you want to check for the existence of a resource but not retrieve it, you should be endpoint (such as a client not having access to that verb and your not handle a 404 error if the resource they're looking for does not exist. REST provides a fair amount of flexibility up to the provider to determine what and how they provide. One important thing to note is that REST is independent from the data that transports it. It is expected that the server and the client will negotiate on how the data is represented.

How a RESTful API server reacts to requests – O'Reilly, Bad user input that the client-side didn't validate. usually means your code isn't properly handling exceptions while processing requests. to which users, so let's “pretend” the requested resource doesn't exist with a 404,  Now that we’ve established that REST is an Integration Style: Do Not expose your platform specific conventions into the REST API. The whole point of using an Integration Style, like REST, is to let different applications developed in different platforms work together, hopefully in a more seamless and less painful fashion.

Your reference for HTTP methods is out of date; you should be referencing RFC 7231, section 4.3.2

The HEAD method is identical to GET except that the server MUST NOT send a message body in the response (i.e., the response terminates at the end of the header section).

This method can be used for obtaining metadata about the selected representation without transferring the representation data and is often used for testing hypertext links for validity, accessibility, and recent modification.

You asked:

resource in REST is a object which is transmitted via HTTP, so maybe i should do processing data but not return them when i use HEAD method?

That's right - the primary difference between GET and HEAD is whether the server returns a message-body as part of the response.

But what i actually need is only to check if data exists in database.

My suggestion would be to use a new resource for that. "Resources" are about making your database look like a web site. It's perfectly normal in REST to have many URI that map to a queries that use the same predicate.

Jim Webber put it this way:

The web is not your domain, it's a document management system. All the HTTP verbs apply to the document management domain. URIs do NOT map onto domain objects - that violates encapsulation. Work (ex: issuing commands to the domain model) is a side effect of managing resources. In other words, the resources are part of the anti-corruption layer. You should expect to have many many more resources in your integration domain than you do business objects in your business domain.

Best practices for REST API design, Best practices on how to design REST APIs to be easy to understand, that any REST APIs handle errors gracefully using standard HTTP codes that We can't manipulate this data as easily on the client-side, especially in browsers. already exists' message to let users know that the user already exists. No, that is not REST. It may be suitable for your purposes if you don't need to use REST, but if you do need to use REST, then that's not right. REST APIs don't predefine URIs like you have done, they embed them in the resources you load. REST APIs define media types and relationships, not URI patterns.

Idempotent REST APIs – REST API Tutorial, Other N-1 requests will return 404 (Not Found) . Clearly, the response is different from first request, but there is no change of state for any resource on server side  May require more work on server side to parse and group the filters. You may have to write a custom URL parameter binder or parser to split the query string key into two components: The field name and the operator. You would then need to GROUP BY (property name, operator). Special characters in variable names can be awkward.

Designing REST API for checking if a username exists. : webdev, Designing REST API for checking if a username exists. The server has not found anything matching the Request-URI. through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. They are a different way of handling component lifecycles and state. Remember that we are using TomEE Plus as our target server, not Tomcat. Tomcat doesn't provide built in JAX-RS support. To test the application, first right-click on the restful Java project, and choose Run As > Run on server. This will deploy the web project and start the Apache TomEE Plus server that hosts the application.

RESTful API Design Tips from Experience - Peter Boyer, If you're going to develop an API for any client service, you're going to want to allow editing of comments without needing a handle for the post for every single route. Shorter paths for updating/deleting resources based on their id . for reliably checking if anything was actually returned, and if not, may  We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud.

Comments
  • What frameworks are you using (if any)?
  • Spring MVC + Angular
  • Spring MVC has implicit support to HEAD. See my answer for details.
  • Ok, good to know about implicit support. So if I understand correctly HEAD method is used to limit response payload, not to limit number of operations executed on server side, right?
  • Ok, thank for your reply. Since this frameworks handle this situation in this way i think, it's better solution. But what are advantages or disadvantages of this solution?
  • @JadenKorr You always can have a method explicitly mapped to handle HEAD requests, but it's not necessary in most of situations. I only would do that if I had performance issues with the framework approach.
  • "I only would do that if I had performance issues with the framework approach. " It dispelled my doubts completely Thanks! I actually have less than 15 reputation, so i can't upvote it, but i will, when i gain more reputation!
  • Yeah, thanks for your reply. But there is any specification which says that i should ( or should't ) process HEAD requests as well as GET requests but without returning content and return only correct HTTP code?
  • There is no specification that says you must or should implement HEAD at all. But if you implement HEAD you should do it as it is described in HTTP specification (in short: same response as with GET but without content). In other side REST architecture forces same endpoint for same resource. But you know, REST is not described by any specification. It is just design pattern. At the end, the way you process both requests is up to you, just request and response are difined.