Error pattern for REST/HTTP APIs
DougBreaux 270007SMYJ Visits (5279)
Discussing with a customer about how to return errors from our "RESTish" API. (Which has existed for a long time, well predating at least our current awareness of good HTTP API practices). Thought I'd document a few things while they're fresh in my memory...
HTTP Response Codes
I'm already a believer in usin
My first cut assumed that it would be normal/reasonable for error responses to be a plain text content type. After all, they're just a status code and maybe an explanatory message.
But after looking more at other APIs, and thinking about how a caller would most easily process replies, it seems better and common to use the same Content Type for both normal responses and errors. So that was the next change. Whatever Content Type the caller has requested (our API supports either XML or JSON), that's the format of error responses as well now.
Single or Multiple Errors?
I thought the norm I'd seen, as a caller, was always a single error returned, so this is what I implemented. But when adding some more sophisticated input field validation (via
That presents 3 options:
Option 1 fit more with what I thought was normal. And, since for an API, it seems normal to me that input validation errors will often or even usually be worked out and removed during development & integration, this was the direction I was inclined to choose. That is, I don't normally expect an application that is using an API to actually rely solely on the API to do any kind of input limi
Option 2 is what my customer wanted, so this is ultimately what I did. Even though he probably won't be the only customer, he's the first and the only for the foreseeable future. Further, after a little research, I determined that both options 1 and 2 seem to be in common use, with no clearly preferred approach.
To me the downside of this approach is having to semantically decide how to handle things differently, depending on whether there are one or more errors. Or even deciding which calls in which states might truly produce more than one, and which wouldn't.
Option 3 I did see some examples of, in articles describing how to design an API, but I haven't yet found any major APIs using that approach. In these examples, the use case for wanting to report multiple errors at once is the very one I hit: input validation. But being able to handle either case seems an unnecessary complication.
My original reason for making this post was to capture the places I'd found that were examples of what APIs did. So, to complete that goal: