How to Handle Business Rules with a REST API

apiapi-designhttprestweb services

I have a REST API to manage a booking system
I'm searching how to manage this situation :

A customer can book a time slot :
A TimeSlot resource is created and linked to a Person resource. In order to create the link between a time lot and a person, the REST client send a POST request on the TimeSlot resource

But if too many people booked the same slot (let's say the limit is 5 links), it must be impossible to create more associations.

How can I handle this business restriction ? Can I return a 404 status code with a JSON response detailing the error with a status code ?

Is it a RESTFul approach ?

EDIT :

Like suggested below I used status 409 Conflict in addition to a JSON response detailing the error

EDIT 2 :

Like detailed in the @Cormac Mulhall, the 403 Forbidden is the most accurate status code for this case

Best Answer

You want to you 403 Forbidden. From the HTTP specs

403 Forbidden: The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.

You shouldn't use 409, it implies that the client might be able to resolve the conflict, which in the case of over booking the client can't do as the conflict rules are server side.

Remember in the context of HTTP status codes "conflict" means a conflict in the state of the resource (in this case the book time slot), for example it expects time in one format and you sent it in the wrong format [bad example, better one would be two clients update a resource at the same time and the server cannot figure out which update to save, like on a version controlled system]. The resource is a time slot, if you change to a different time slot you have created a different resource, not resolved a conflict with this resource.

409 Conflict: The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.

The server should return 403 Forbidden with an explanation that it is refusing to save the state because that time slot is already full. Nothing the client can do in altering the state of the resource can change that. The client should not re-submit. They must instead create a new time slot instead (you could return the closest free slot as a suggestion).