The documented one. It is hell to work with APIs where only the happy path is documented.
Programming
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Rules
- Follow the programming.dev instance rules
- Keep content related to programming in some way
- If you're posting long videos try to add in some form of tldr for those who don't want to watch videos
Wormhole
Follow the wormhole through a path of communities [email protected]
Anything except the 2nd to last one, which is, unfortunately, mandated by my employer's internal code style guidelines. π«
The status code that gets returned should be the status code of the messenger and not the data. If you want to add a status code about the data, then please do.
If something can return null and empty and it's valid, that is not a 404. That is a 200.
As far as a 403, the messenger is telling you that you shall not pass. There is no data. 403 is appropriate here. The return response can be anything since 403 is pretty self explanatory, but I would probably return json to be consistent. I would also use the field message. Something like the first one for this use case only.
In other cases where i do get data, I would use data, message, status (optional). But status in the json response would be status about the message.
For me it just depends on what I expect. They're all relatively the same thing. As long as the status code is appropriate (403), it doesn't matter whether it's JSON or plaintext. Ideally the API would respect and handle the request header, and return plaintext if you request plaintext.
I'm a data engineer, and have seen an ungodly ammount of 200-but-actually-no-stuff-is-broken errors and it's the bane of my life!
We have generic code to handle pulling in api data, and transforming it. It's obviously check the status code, but any time an API implements this we have to choose between:
- having code fail wierdly further down the line because can't parse the status
- adding in some kind of insane
if not response.ok or "actually no there's an error really" in response.content
logic
Every time you ignore protocols and invent your own, you are making everyone sad.
Will take recommendations of support groups I can join for victims of terrible apis.
#4 for me.
Proper HTTP Status code for semantic identification. Duplicating that in the response body would be silly.
User-friendly "message" value for the lazy, who just wanna toss that up to the user. Also, ideally, this would be what a dev looks at in logs for troubelshooting.
Tightly-controlled unqiue identifier "code" for the error, allowing consumers to build their own contextual error handling or reporting on top of this system. Also, allows for more-detailed types of errors to be identified and given specific handling and recovery logic, beyond just the status code. Like, sure, there's probably not gonna be multiple sub-types of 403 error, but there may be a bunch of different useful sub-types for a 400 on a form submission.
1 or 3; maybe 4.
With several assumptions made, ultimately, they're asking for json, and we should still return json, but what that looks like is up to you. It should be static enough that the person on the other end can write:
If json.grtnode(error) == "unauthorized access"
Do stuff
Ifnyour going to be changing the text with some regularity to contain relevant information for the error (eg, an item ID, that is now invalid), then consider a code/text and additional fields.
JSON Problem Details
https://datatracker.ietf.org/doc/html/rfc9457
- It has a specification, so a consumer of the API can immediately know what to expect.
- It has a content type, so a client sdk can intelligently handle the response.
- It supports commonly needed members which are a superset of all of the above JSON examples, including type for code and repeating the http status code in the body if desired.
- It is extensible if needed.
- It has been defined since at least 2016.
This specification's aim is to define common error formats for applications that need one so that they aren't required to define their own ...
So why aren't you using problem details?
1, 3, 4 are good but out of laziness I'd personally use the first.
At a previous job we had an unholy combination of the last two:
HTTP/1.1 200 POST /endpoint
{
"data": null,
"errors": ["403", "unauthorized"],
"success": false
}
That really is unholy and I also couldn't work there long if they thought that was OK (pun intended).
It's a perfectly fine way of doing things as long as it's consistent and the spec is clear.
HTTP is a transport layer. You don't have to use its codes for your application layer. It's often done that way but it's not the only way.
In the example above the transport layer is saying "OK I've delivered your output" which is technically correct. It's not concerned with logical errors inside what it was transporting, just with the delivery itself.
Don't use JSON for the response unless you include the response header to specify it's application/json
. You're better off with regular plaintext unless the request header Accept asked for JSON and you respond with the right header.
That also means you can send a response based on what the request asked for.
403 Forbidden (not Unauthorized) is usually enough most of the time. Most of those errors are not meant for consumption by an application because it's rare for 4xx codes to have a contract. They tend to go to a log and output for human readers later, so I'd lean on text as default.
I would actually encourage error responses be in JSON if your 200 responses are JSON. Some clients are apt to always convert the body to JSON so it could avoid an exception on the client side not to throw a curveball.
To your point it's most important that the content and Content-Type header match.
If any client app is blindly converting body to JSON without checking (at the very least) content type and size, they deserve what they get.
If you want to make it part of your API spec to always return JSON that's one thing, but don't do it to make up for poorly written clients. There's no end of ways in which clients can fail. Sticking to a clear spec is the only way to preserve your sanity.
Is the last one real? Has any sane dev made something like that monstrosity? It's not like the others are any better, but who would ever think of doing the last one and why?
I have worked for financial institutions that have variations of the last one. If I saw it I wouldn't even blink. Semi realistic reasons might be:
Status attribute - because the project is using the base library of [project whatever] which was the brain child of eNtErPrIsE aRcHiTeCt whose hands on skills are useless and the off-shore dev team who assigned [random newbie] because that's who was available at the time. They used a status attribute because they didn't know how to get the status of the http response. No-one with budget control is interested in hearing about technical debt at the moment. Everyone has to use it now else the poorly written test classes fail.
Message code: because "we need codes that won't ever change even if the message does". Bonus points if this is, in fact, never used as intended and changes more frequently than...
Message: "because we still need to put something human readable in the log". Bonus points x2 if this is localised to the location of the server rather than the locale of the request. Bonus x3 if this is what subsequent business logic is built on leading to obscure errors when the service is moved from AWS East Virginia to AWS London (requests to London returning "colour" instead of "color" break [pick any service you never thought would get broken by this]).
I have seen it all etc
Of those options I'm going with the last one. Because you have the standard error number right there but I'm assuming that it's a customer response so the message could be modified to have something useful in it.
A simple error code is sufficient in all of these cases. The error provided gives no additional information. There is no need for a body for these responses.
There may be a need for additional information, there just isn't any in these responses. Using a basic JSON schema like the Problem Details RFC provides a standard way to add that information if necessary. Error codes are also often too general to have an application specific meaning. For example, is a "400 bad request" response caused by a malformed payload, a syntactically valid but semantically invalid payload, or what? Hence you put some data in the response body.
A plain 400 without explanation is definitely not great UX. But for something like 403, not specifying the error may be intentional for security reasons.
I know of some people that never use 403, but instead opt for 404 for security reasons. 403 implies that there is something they could have access to, but don't.
I think in some situations that this can be valid, but it shouldn't be a crux.
404 is definitely also used sometimes for hiding stuff that shouldn't be seen, but 403 may still be appropriate for various stuff where there is nothing to hide. With 404 you probably also never want to give any explanation or error message.
I like using Problem detials
It's fully supported by the .net server pretty much out the box and just seems nice to stick to a standard where possible.
Have a code, where you can really describe the error; try to use the correct HTTP status (your example doesn't); don't ever use status 200 for errors; and finally, have an "error" key set to something somewhere (I'd write the error code to it).
The message is optional.
So, the simplest version would be:
HTTP/1.1 401 POST /endpoint
{
"error": "UNAUTHORIZED"
}
Status 200 for errors is common for non-REST HTTP APIs. An application error isn't an HTTP error, the request and response were both handled successfully.
Anything but the last one. Don't duplicate the http code in the body, else you're now maintaining something you don't need to maintain.
I'm not a fan of codes that repeat information in the body either, but I think if you had used a different example like "INVALID_BLAH" or something then the message covered what was invalid, then it would be fine. Like someone else said, the error data should be in an object as well, so that you don't have to use polymorphism to figure out whether it's an error or not. That also allows partially complete responses, e.g. data returns, along with an error.
A mix between the last one and the previous. The key error
should be set in order to indicate the presence of an error, while status
and code
represents, respectively, the error numerical code and the error type, while the error message
is supposed to be concatenated to an human-friendly error text.
That clown emoji would make me think the company has alt-right sympathies
HTTP/1.1 403 UNAUTHORIZED
{
"error": {
"status": "UNAUTHORIZED",
"message": "Unauthorized access",
},
}
I would separate the status from the HTTP status.
- The HTTP status is great for reasonable default behaviours from clients.
- The application status can be used for adding more specific errors. (Is the access token expired, is your account blocked, is your organization blocked)
Even if you don't need the status now, it is nice to have it if you want to add it in the future.
You can use a string or an integer as the status code, string is probably a bit more convenient for easy readability.
The message should be something that could be sent directly to the user, but mostly helpful to developers.
It's 401 unauthorized or 403 forbidden, not 403 unauthorized
to be even more pedantic, if we follow the relevant official RFCs for http (formerly 2616, but now 7230-7235 which have relevant changes), a 403 can substitute for a 401, but a 401 has specific requirements:
The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.
(the old 2616 said 403 must not respond with a request for authentication but the new versions don't seem to mention that)
Youβre right, I was just giving an example though.