Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use custom reasons for an HTTP status code to differentiated between errors for a REST API

I want to differentiate between separate types of "Not Found" errors. For Example given the following request:

GET /author/Adams/works/HHGTTG

Either the author could be 'not found' or the work could be'not found' and I want to differentiate between the two.

status: 404 - author not found
status: 404 - work not found

According to the spec the reason phrase can be changed. http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

6.1.1 Status Code and Reason Phrase

...The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol...

Is it also acceptable to use two unique phrases for the same status code?

And, is this a sound approach or is there a better convention for indicating more granular errors?

Ultimately I want to have a client library that could throw either an AuthorNotFound or WorkNotFound exception instead of a generic AuthorOrWorkNotFound exception.

like image 467
Ben Avatar asked Jan 04 '11 17:01

Ben


2 Answers

You could have the body of the HTTP response contain a message which you can parse with any additional information.

The HTTP status message on the status code (in the response) can be anything you want and it won't effect any clients. HTTP clients usually ignore the message text.

like image 190
Brian R. Bondy Avatar answered Sep 30 '22 13:09

Brian R. Bondy


When using your "shadowed" not found approach, you could do use 404 with response body:

  • use 404 status with text details ('author not found', 'work not found'). To be more language flexible you could use labels (like error.author.notFound)
  • use more structured and much easier to parse "subcodes" (e.g. 10 stands for author not found, 11 user not found).

Still I do NOT recommend above mentioned sub-codes, they add a lot of complexity and maintenance effort for uniform HTTP interface. Structure your api-client library differently. Let it call /author/adams/work/11 first. If it returns 404 then call /author/adams/ next to find out whether it was the missing author which caused the 404. You then can throw respective NotFound exceptions.

Another alternative is to design the end api-client application differently. It first should call /author/adams then if not 404 would proceed /author/adams/work. So naturally the application itself is descending the path. But this of course only works if your page flow inside frontend adapts to this call sequence.

like image 24
manuel aldana Avatar answered Sep 30 '22 14:09

manuel aldana