DEV Community

Discussion on: The HTTP Status Codes You Need to Know

Collapse
 
reritom profile image
Tomas Sheers • Edited

I use the Mozilla http status thing developer.mozilla.org/en-US/docs/W...

But I'm wondering, if the client sends a request to a RESTful api to create something like a resource allocation, where the request and references are valid, but the allocation already exists and so therefore another can't be made, what status code would be best to reflect that?

The 406 title seems correct for this, but the description seems to technical.

409 could work if you consider conflict as a functional conflict.

I don't seem to find a good HTTP code to reflect that the payload and request was valid, but the resource couldn't be created for functional reasons.

Collapse
 
markmichon profile image
Mark Michon

When creating a resource, ideally you'd have some mechanism in place to dynamically generate the unique references(ID, etc).

If, however, you're creating user accounts bound to a user id or email, you may run into a scenario like the one you've mentioned. In that case, the 409 seems more appropriate if you want to avoid the generic 400. I wouldn't use 406.

Collapse
 
reritom profile image
Tomas Sheers

This is what I would expect, but Coreys reply makes sense too. I wonder if there is some specification for this, or what the general consensus is.

I've worked with a few REST APIs and most haven't been consistent in this regard.

Collapse
 
xanderyzwich profile image
Corey McCarty

I'd typically consider such a thing as 200 with a response that includes some sort of error/exception code/explanation. The thing already exists, but the request was received, processed, and responded to appropriately. This should be a part of your contract design for the API itself. I personally believe that something that is data related shouldn't return http code other than success. Perhaps adoption of 201 as successful creation/allocation and 200 as non-error without creation having occurred.

Collapse
 
reritom profile image
Tomas Sheers

I haven't considered using 200 before for valid requests that can't be processed. But it does make sense. I've typically used: 200 OK (for getting valid resources, and for resource deletions), 201 for resource creation, 404 for invalid resource ids or missing routes, and from there I just imagined that a 4XX code would be used to indicate that the request was functionally invalid.

This was based on seeing some consumers of APIs where in python they would do "response = requests.get(...)" and then check if the response is "ok" by using "if response.ok: ...". So that in that case 2XX is ok, and anything else is not ok, so one would expect the failed resource to be in the "not ok", so not a 2XX. But this was just extrapolation. Maybe it is better for all valid requests to be 2XX, but would require more client side logic.