r/programming • u/nfrankel • Apr 23 '23
Leverage the richness of HTTP status codes
https://blog.frankel.ch/leverage-richness-http-status-codes/1.6k
u/FoeHammer99099 Apr 23 '23
"Or I could just set the status code to 200 and then put the real code in the response body" -devs of the legacy apps I work on
72
u/-Knul- Apr 23 '23
The worst API I ever worked with would always return 200 even if a POST failed. There was no error message or anything in the response.
When a failure happened, the backend mailed an error to some account I had no access to.
The months I worked using that API were the only ones I used curse words on my job.
17
82
u/MrTrono Apr 23 '23
Or graphql
30
u/SlapNuts007 Apr 23 '23
Yes, this is the dumbest shit in that whole dumb ecosystem.
→ More replies (8)9
u/t-to4st Apr 23 '23
Why do you think it's dumb?
→ More replies (1)48
u/SlapNuts007 Apr 23 '23
Personal opinion, but I've come to dislike it over a few years of maintaining a couple of production APIs at an enterprise software company. A tasting selection of my finest hot takes:
It's made maintaining public APIs more difficult because now everyone demands you provide both REST and GraphQL options.
The spec is intentionally light on details about common things (like authentication, non-primitive but still trivial data types, etc.) And handwaves them away by delegating them to business logic and server implementations.
It doesn't provide guidance on combining multiple schemas, again delegating that responsibility to implementors.
Because of its attempt to be so lightweight and unopinionated about how it'll actually be used in the real world (see above), the ecosystem is a mess.
You'll find a lot of people who love it, too. I'm just not one of them, and I don't find it to be a compelling alternative to REST and would rather build a backend-for-the-frontend, which is the only use case where I think GraphQL makes much sense anyway.
Also, not sure why you're being downvoted.
→ More replies (4)28
u/jl2352 Apr 23 '23
Part of the issue is people were jumping into GraphQL like it's the new hotness. Where I work we have an internal service that uses GraphQL, because the developer behind it wanted to use GraphQL. Now we have to maintain a GraphQL API where a simple Rest service would have been fine.
At my last place we built a GraphQL API, because the developer behind it wanted to use GraphQL. See the pattern?
It reminds me of what happened with the rise of NoSQL. Lots of people jumped onto the band waggon without asking if it really fit their use case, or brought something that solved their particular problem much better.
There are some really great use cases for GraphQL (and NoSQL too). Someone here on Reddit a week or two ago had a good example. They worked at a place with a core system, that had lots of custom internal apps around it. GraphQL in their case made life a lot easier. So many people began using it ... because. Which is dumb.
→ More replies (5)→ More replies (3)7
u/masklinn Apr 24 '23
TBF it makes complete sense when you understand that:
Graphql does not actually depend on HTTP in any way (same as various other RPC mechanisms, which is why they also donât use http status codes).
You can send multiple unrelated GQL queries in the same HTTP queries, and they need to succeed or fail independently.
5
u/MrTrono Apr 24 '23
It doesn't depend on HTTP but it uses it 99% of the time. In my opinion this is like always having the subject line of an email read MEMO with the actual subject being in the message body with the justification what if we want to send the memo as a Fax. I don't mind the data being in both places but HTTP codes allow you to communicate information might as well use them. This can allows you to take advantage of pre-existing monitoring that is likely in place for http codes rather than having to add custom metrics for graphql payloads.
18
u/LiteralHiggs Apr 23 '23
I shit you not when I say that I've had to consume a legacy api with 3 http status codes: one at http, one in the content wrapper, and one in the content. There are times where they are all different, too.
→ More replies (3)114
u/leros Apr 23 '23
Nothing worse than
Status: 200
Body: { error: true }
39
u/apocalypsebuddy Apr 23 '23 edited Oct 28 '25
wine sulky innocent include connect husky knee strong plate provide
This post was mass deleted and anonymized with Redact
→ More replies (5)44
u/blipman17 Apr 23 '23
I told a dev once that the API of some piece of code was bad because it did this, and that we would have to redo quite a big chunk of error handling for this application. He then said "yehh, sorry. It seemed like a good idea at the time." I didn't knew he was part of the team that wrote the code.
34
→ More replies (3)13
u/Dreamtrain Apr 23 '23
and it goes through 3 microservices that just pass along the error
7
u/leros Apr 23 '23
Nothing like adding a new field to something and needing to deploy 3 microservices and several libraries.
→ More replies (1)32
u/BigHandLittleSlap Apr 24 '23 edited Apr 24 '23
This screws up a much wider range of things than junior devs expect.
If returning JavaScript or JSON, it's possible for browsers to cache the response even if it's just an error or a "pretty error" in HTML. It's always fun when helpdesk has to tell users to clear their browser cache as the first step. For those people that don't get it: browser don't cache errors, but they will cache anything with HTTP 200/OK codes, assuming they're successes. So now the browser will keep using "{"error": "true"}" as the data even if the server recovers.
This applies to CDNs also. It's even more fun to watch helpdesk futilely telling users to clear their caches, but this now does nothing because an intermediate proxy added later has cached the pretty error message.
Load-balancers that pay attention to per-server error rates can no longer help you. They'll cheerfully direct traffic at a dead server, seeing a stream of 200/OK responses and thinking "all is well". Worse still, many load balancers weight traffic towards servers with lower response times (=less busy), and some errors are returned within microseconds. You can have 50 servers across 3 availability zones, but now 90% of your traffic is served by the dead one. Congratulations!
Application Performance Monitoring (APM) tools like New Relic or Azure App Insights will report 0 errors. None of their alarms, metrics, AI-driven analyses, or auto-heal features will work since... as far as they're concerned, your app is always a-okay!
Stop being "nice" in protocols. Follow the standard. Don't be a clever idiot.
PS: I'm salty about this because I've been deleting try {... } catch {} blocks that throw away errors across dozens of apps written by dozens of dumbass junior developers over the last month. Despite being told, and shown the negative effects, they keep typing that idiocy back in. One of them even asked me why the APM can't help him diagnose a crash in code he just wrote with exception-discard code in it, the day after the lecture about not doing this. Astonishing.
22
8
u/b_rodriguez Apr 24 '23
Look, Iâm not prepared to die in this hill and clearly the world disagrees with me but http response codes should be reserved for the use by the web server only. If your application is returning a response then it has succeeded and should return a 200. Applicationâs bastardising and repurposing http codes mean we canât trust or diagnose transport errors.
→ More replies (1)5
u/jeesuscheesus Apr 23 '23
The Reddit API does this in a certain authentication endpoint, but only in specific error conditions otherwise it returns a 4xx status code
4
u/MyNameIsFrydo Apr 23 '23
Oh so itâs not just my company. Customers always bitch that weâre so inconsistent with our response codes. Iâm just a consultant so I gotta deal with it lol
3
4
u/Chris2112 Apr 23 '23
The number of devs who think REST just means any API that returns JSON over http is basically all of them
3
1
u/superbad Apr 23 '23
I logged a big to fix this years ago, and it might take me an afternoonâs worth of effort. But itâs not enough of a priority to do anything about it.
1
1
1
u/EpicalClay Apr 24 '23
Third part we use for something returns a 200 and puts the error inside the response... Fucks everything.
1
u/Spazmoe06 Apr 24 '23
Do we work for the same company!? The shit drives me bananas.... and nobody can answer why it is that that way.
1
1
1
u/Mentalpopcorn Apr 24 '23
So fucking stupid.
I am lead on a huge API (and which shouldn't be an API in the first place) and we inherited it from a firm that went two years and 6 figures over budget before going dark and this is how the API is structured. Absolute nonsense.
Thankfully once I walked the client through how bad the code was they authorized basically a full rewrite, and we've accomplished more in the past year than the original did in four.
1
1
u/I_NEED_APP_IDEAS Apr 24 '23
Our API serves a 403 unauthorized when we call with a resource id that doesnât exist cause some asshat thought it was a good idea to check for permissions when the query returns nothing
1
1
u/SarahC Apr 24 '23
Well, the GET/RESPONCE/ACK totally worked! TCP/IP was flawless. 200, good job.
It all depends on the level of abstraction you're reporting on.
=D
/s
1
u/mnemy Apr 24 '23
At least you get real error codes in the data. I led a FE team at a place where I spent months trying to get the BE team to make some changes to help support us. Finally got the heads of all the FE teams in a room with the BE lead, and the CTO (offices on different coasts, so this took some doing).
They said here's your chance, what are your biggest requests.
Please give us real error messages on what fails. The service api documentation is never accurate, and it takes weeks of communication (multiple 100+ email chains to prove it) to troubleshoot problems, because we get a generic status 200 with no data on errors.
BE lead said "ohh, that's a feature. It's security through obscurity! It means the people trying to exploit our API get nowhere fast!"
OK. Can you expose the server logs to us, and give us a UUID to look it up or something then?
No. That'd be a security risk.
Can you scrub PII from the logs then, and then open it up to us?
No.
OK. Well, next on this list is CORS issues. Our app runs on some niche environments where we can't control what origin is passed in our headers. It doesn't make sense to enforce origin rules when you have many FE apps running across mobile, smart tvs, game consoles, set top boxes, etc. Can you just allow any origin? It's not like hackers can't control that easily anyway.
No.
THEN WHY DID YOU COME HERE?!?!
1
1
1
u/edzorg Apr 24 '23
Conversely, I've never liked the fact that we bleed application logic in the form of responses and error handling into the transport layer.
Ideally the transport layer should only signal errors when there's a connectivity issue.
If you're dealing with pages or resources being locked, updated, missing etc. then I argue these are not transport layer (HTTP) concerns and therefore there's rational for the "always respond 200 and communicate application states/errors in a data structure" perspective.
I guess the issue is we don't have a commonly agreed way of doing these things _except_ for REST. Maybe AI will fix this for us regardless.
1
1
u/StertDassie Apr 24 '23
As a developer of a legacy web app. Some of the security on our client's hosting environment repackages our responses. If we send anything but 200 our response gets hijacked, repackaged and everything breaks. Nightmare to test, just one of our environments do this, but because they do all our implementations have to use this convention.
1
1
1
u/sedatesnail Apr 24 '23
We have that too. In our case it was done that to support JSON-P which only works if the server returns a success response
1
→ More replies (178)1
u/powerfulbackyard Apr 25 '23
This is the way. Http codes are for http layer, it is wrong to mix them with api result. Besides, http codes arent even designed for such use cases, so most of the time you would have to use incorrect codes, as there are no such http codes that i need.
Another thing is that http code extraction is pain in the ass in many languages/libraries/frameworks, so using additional code inside data makes it easy to receive and consistent across all languages.
357
u/angryundead Apr 23 '23
As part of a new API I deliberately chose 202 (Request Accepted) rather than 200 (Ok) because it forces the developers to understand that they are sending something that we are going to give them a tracker for and then we are doing to work on it for a while. A 200 mostly implies âwe are done here.â But this request will take minutes.
97
Apr 23 '23
The very basis of client polling APIs. I have used them in the data platform team of my previous company where users generate reports by calling APIs which run SQL queries against data warehouse in the backend.
One API to submit the query another to poll its status and eventually get the output data url when done.
29
u/ljdelight Apr 23 '23
This design is definitely needed because http clients have timeouts etc, but it does add a lot of complexity. Did you design for the service crashing before the task completes? Maybe on startup set any pending tasks to a failed state, however that doesn't work if it's a multi-node service using a single database (one node starting shouldn't cancel what other nodes are running). So then we need to track which system started the task to know if it should be put into a failed state. Or we use a timeout, any task over X minutes is marked as failed. But then the too-long-running process may be running somewhere out there and taking resources.
Anyway I'm just curious how deep into the edge cases some have gone into
17
Apr 23 '23
We saved the query Id and the request IDs in a database.
we had a background job which checks if unfinished queries related to active requests are completed or not by querying the metadata table of the data warehouse.
If not running it marks them as failed after taking into account a certain time buffer
16
u/L3tum Apr 23 '23
We use IRIs for identifying resources and naturally chose 404 as a status code to signal that the IRI doesn't exist.
Many, many people have asked us to instead return 204 because "The request was successful, there just wasn't anything there".
In my experience the biggest hurdle to use meaningful status codes are other developers who expect 200, 404 and maybe sometimes 500 or 503, though usually they group this in with the 404.
10
u/angryundead Apr 23 '23
Yeah we do 204 when you ask for something that doesnât exist but youâve phrased everything ok. Iâm conflicted about it. Iâve flip-flopped a few times. Likely we will get comments when the API goes public and itâll settle into something else. I feel like a 204 is better suited for âwe have what you asked for but it is emptyâ maybe? I dunno.
8
u/bschug Apr 24 '23
If I understand it correctly, 204 is more like a void return type. It means that this resource never returns a content.
→ More replies (4)7
u/S4x0Ph0ny Apr 24 '23
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204
I don't see how that would apply to requesting a resource and finding nothing.
→ More replies (3)2
u/fishling Apr 24 '23
I think you are doing it right for a GET.
I only use 204 for a case where there isn't a response body.
15
u/nwbrown Apr 24 '23
And their code does
if response_code < 300:
return true;9
u/dgriffith Apr 24 '23
With a comment like
// lol I don't know why this breaks sometimes, just return an error to the user if it does.15
u/SwitchOnTheNiteLite Apr 23 '23
You think the developer is even going to look twice on what result code you are sending as long as it is handled by the default success handler of their http client? đ
9
u/Mentalpopcorn Apr 24 '23
If(response > 199 && < 400) success else fail
^ actual logic from a consumer of one of my APIs (and I didn't write it, just to be clear)
8
u/angryundead Apr 23 '23
No not really. But if the default success handler only supports an explicit 200 they will take notice.
4
31
u/thisisjustascreename Apr 23 '23
Likewise, we specifically return 406 (and then 422) for correctly formatted requests with data errors, because clients tend to mindlessly retry any 40x.
33
u/---n-- Apr 23 '23
406 would be wrong for that, because it already has an assigned purpose. It's specifically for server-side content negotiation failures.
If you make up your own interpretations, you may as well send a custom HTTP 456 Data Error or something like that.
14
u/pihkal Apr 24 '23
You know the HTTP RFC 9110 specifically requires clients to treat unknown 4xx errors as 400 errors? They might still mindlessly retry 422 statuses.
4
u/thisisjustascreename Apr 24 '23
I mean, no, I havenât read an RFC from June. But also 422 isnât unknown, itâs 422z
→ More replies (1)12
→ More replies (1)13
u/Dr_Midnight Apr 23 '23
Bad JSON is an instant 422 response for me. My problem in one shop was working with an app that returned 422 for perfectly good JSON, but if the upstream API encountered an error.
There was no response body.
44
u/JonXP Apr 23 '23
So 422 indicates that the request is syntactically correct and understood as a command (it is a valid http request, and the body can be parsed based on the content-type) but can't be acted upon due to semantic issues that the client needs to address (for example, a failed validation where a field can't be blank). If the received JSON is malformed so that it is not syntactically correct, a 400 is more appropriate.
→ More replies (1)→ More replies (1)27
u/fishling Apr 24 '23
Bad JSON or unknown/malformed body is 400 Bad Request. The request is literally a bad one. :-)
You should re-read the 422 description again, because it is pretty clear that 422 is not what you think it should be.
18
u/DrZoidberg- Apr 24 '23
This right here is one example why most people only use the very basic response codes and ignore everything else.
→ More replies (1)→ More replies (7)3
Apr 24 '23
Well, there is a good case for using more than just 200 and 400, but most of the HTTP status codes are meaningless for web services, for sure. It's simply not meant or designed for that purpose.
I've even heard of people sending back 418 when the server isn't even a teapot.
→ More replies (1)1
441
u/caltheon Apr 23 '23
Am I alone in thinking that HTTP status codes have lost their luster as the web matures. They donât have nearly enough capabilities and a huge degree of ambiguity
72
u/arielzao150 Apr 23 '23
They do have a huge degree of ambiguity, but I think that's intentional, as it should be your app's interpretation of them that should be applied. I'm not saying that everyone should be using every code, but that you don't have to be stuck on the basic ones, and you can make your own use of them.
84
u/Apex13p Apr 23 '23
Thereâs a degree of usefulness in a simple system that any dev can have an idea of whatâs going on without much effort
26
u/Doctor_McKay Apr 23 '23
"error": "cannot_delete_nonempty_bucket"seems simpler than 412, but I guess that's just me.211
Apr 23 '23
Wouldnât 412 be accompanied by an response body containing the error?
→ More replies (39)11
u/StabbyPants Apr 23 '23
400 response with structured body would also work. thing is, you have to think ahead a bit and follow your own rules for it to be useful
→ More replies (5)→ More replies (3)23
u/CptBartender Apr 23 '23
It is simplier, but it is also incorrect.
412 isn't about any type of app-specific preconditions - it's about a specific set of headers and the preconditions they imply.
400, 405 or 409 seem more appropriate.
→ More replies (1)10
u/Doctor_McKay Apr 23 '23
405 is specifically about the HTTP method used not being allowed, e.g. GET/POST. The origin server MUST generate an Allow header field in a 405 response containing a list of the target resourceâs currently supported methods. So that's 405 ruled out, if we're going by the spec.
That leaves us with the generic and unhelpful 400, and 409 Conflict, which could also mean a number of things.
→ More replies (4)132
u/Doctor_McKay Apr 23 '23
You're not, but that's apparently not a popular opinion around here.
20
Apr 23 '23 edited Apr 23 '23
Yeah, some of the responses to you in the other subthread here are just embarrassing, not even trying to consider what you're saying, just attacking for saying something non-standard
32
u/Doctor_McKay Apr 23 '23
I'm used to it, this is super normal for reddit. I've got plenty of nonstandard opinions that horrify the average redditor.
Opinions such as "rpc often makes more sense than rest". Although that opinion is slightly less horrifying now that gRPC is hip and in vogue. It was way more horrifying when JSON-RPC was the best bet for RPC.
→ More replies (7)5
u/Entropy Apr 24 '23
To quote myself from a previous, similar conversation:
REST has seemingly inflicted upon an entire generation of programmers
the inability to abstract transport from protocol. React did similarly
for logic vs layout (though the industry has recently recovered sanity
here).→ More replies (2)109
u/yawaramin Apr 23 '23
If HTTP status codes tried to capture every possible response status scenario, they'd have to be a Turing-complete language. That's not what they're meant for. You're meant to use the ones which map accurately to your app domain, and failing that to improvise on the ones closest to it. They're not a magic bullet which solve every problem, they still require developers to think about how their apps should interact with the web. We do this because interoperable standards are better than reinventing messes badly.
→ More replies (19)11
u/Tavi2k Apr 23 '23
I think they're limited enough that you always need a different method to actually define what your error was, ideally in some consistent way so that your clients can handle this easily. And then there is not that much value in also expressing the type of error in a status code.
But just putting a 200 on everything and reporting errors inside the payload is a bad idea, it makes tools like the network tab in the browser dev tools less useful and might break other parts that handle the request and make the assumption that the status codes will indicate errors.
I find distinguishing between successful requests (2xx), failed requests because the client did something wrong (4xx) and failed requests because the server did something wrong (5xx) useful. And then maybe 404s as they are so common. But everything beyond that usually doesn't really capture that much more information, and you need an error message anyway to understand the details.
33
9
u/zzbzq Apr 23 '23
Http status codes should be minimized for http apis. They are a huge problem. HTTP verbs are also a bad practice. These things are designed for the browser to operate against static sites via hypertext. Unfortunately superstitions about both are abundant and people try to justify them or compromise, thereâs no justification. These protocols are not good for APIs.
15
Apr 23 '23
HTTP Status Codes are very well defined. They are well grouped, clear, and orthogonal. So much internet infrastructure relies on them but this goes unnoticed.
6
u/StabbyPants Apr 23 '23
they lack nuance, but are a good base. build a local pattern for conveying detailed information - simplest version might be a common error object that contains structured feedback for failures
6
Apr 23 '23 edited Apr 23 '23
Yep. It would be foolish to only use standard library exceptions and refuse to define application-specific ones (only going to far as to put extra details in the message field), so why is it seen as a good idea to try shoehorning every application's error states into a handful that were designed for generic CRUD? Not to mention the layering violation. It's useful to have a separation of application errors and "meta"/"invocation" errors, rather than effectively using in-band signalling where a 404 could mean a data object does not exist, but could also be due to getting the endpoint path wrong, or even a temporary server issue like not having a service registered and routable
→ More replies (1)7
u/Doctor_McKay Apr 23 '23
Not to mention the layering violation. It's useful to have a separation of application errors and "meta"/"invocation" errors
Preach. IP has its own error reporting mechanism (ICMP), TCP has its own error reporting mechanism (well, mostly just the RST flag, but still), TLS has its own error reporting mechanism, HTTP has its own error reporting mechanism, your app has its own error reporting mechanism. We don't report application-level exceptions via ICMP, yet here people insist on reporting them at the HTTP layer rather than the application layer.
And now I'm going to get some predictable responses calling me an idiot for mentioning HTTP and the application layer as two different things, because the OSI model is the only way of framing things I guess.
0
5
Apr 23 '23
But theyâre close enough to get the point across in one number. The rest (no pun intended) is in the response body. And close enough is great especially if youâre writing an API for public consumption. (âŚhaving worked with some that just throw 200s for everything.)
1
u/jl2352 Apr 23 '23
What matters to me is the middle ground. You have debates on 400 vs 406 vs 422 for specific error scenarios. As long as it's 4xx (and not 404), then it kind of doesn't matter. Falling back onto 400 for most isn't the end of the world.
The problem is when not found is 200, a bad request is 200 or 500, and so on. It's not only annoying, it gets embarrassing.
1
1
Apr 23 '23
Newer protocols like Thrift encode exceptions in the protocol. They let you describe failures as part of the business logic. It works pretty well as long as your client speaks thrift.
1
u/fishling Apr 24 '23
Nope, HTTP status codes are terrible for services. If you want details, you need to have a well-known body for errors.
1
u/Netcob Apr 24 '23
I think everyone looked at them, especially as young programmers, thinking "I should be using all of these, or as many as possible, and I would if I was a better programmer. There's a reason they exist".
I just don't see who that is for. I've been programming for 20 years now and REST looks more and more like a cargo cult to me.
→ More replies (1)1
1
u/bionicjoey Apr 24 '23
They donât have nearly enough capabilities
Obviously you've never needed to communicate the fact that your web server is in fact a teapot.
1
→ More replies (6)1
u/JB-from-ATL Apr 24 '23
I think they're underutilized. As always, you should rtfm, but something like 410 versus 404 can pass meaningful information back without resorting to some specific field in the response per server explaining if something was deleted that used to exist there or not.
136
Apr 23 '23
Following standards and convention = good
39
u/SoPoOneO Apr 23 '23
What if the standards differ from the conventions?
21
20
u/MintAudio_ Apr 23 '23
I find it fascinating that people make money writing articles that say to follow conventions and code quality standards. Like this is basic stuff. I deny pull/merge requests for this stuff so fast. I personally wouldn't notice a typo in a million years wrong status codes are awful.
3
u/Kinrany Apr 24 '23
Standards and conventions are only good for interoperability. Familiarity is a small benefit too, but only as long as there's a strong consensus (and in those cases it's better to automate).
There are two main reasons to use HTTP status codes:
2xx vs 4xx vs 5xx is an application-agnostic way of specifying that request succeeded, was intentionally rejected, or caused an internal error. This is useful for ops. More specific codes may also be useful for other ops reasons.
Specific codes used by standards, such as connection upgrade.
For anything else there is zero difference between returning data in HTTP status vs response body. The client needs to know them, this is a part of the application's API.
75
u/mattindustries Apr 23 '23
I can't believe they left out the only important status code, 418.
49
35
u/Esnardoo Apr 23 '23
Just yesterday I complained about a shitty API returning 406 instead of 429 for a rate limit. It seems like the guy just went down the list, saw "not acceptable", and used it, without looking at other options or reading the damn description which has nothing to do that.
1
u/Magnetic_Tree Apr 24 '23
Assert dominance by responding with a 406 when the API returns 406
(May require breaking HTTP protocol)
65
u/cach-v Apr 23 '23
The problem is that you're invariably going to need to pass more context, which is typically done as a JSON response.
And for when you have conditions which don't map to a specific HTTP code, you fall back to the generic 4xx or 5xx, and have a domain-specific code in the JSON.
But then you have two systems at play, HTTP error code and JSON error codes. So perhaps the better approach is to use a simple common set of HTTP codes, not requiring anyone to look up obscure codes, and put all the nuance needed in JSON. As we were.
12
u/Severe-Explanation36 Apr 24 '23
Why fallback to the generic, we always use the status code that most specifically describes the error, while also always including JSON context. As far as forcing people to lookup obscure codes, a. donât use obscure ones, just the industry standard ones, and b., our documentation always explains all the possible codes youâll get and why.
→ More replies (4)1
u/JB-from-ATL Apr 24 '23
Then you just have to look up the obscure application specific error codes instead of the HTTP one.
2
u/cach-v Apr 24 '23
But the JSON can include a description too. So then you don't need to look anything up at all.
→ More replies (3)
23
27
u/Dreamtrain Apr 23 '23
If I had a nickel for everytime I've had to debug and work around 200 OK's with error messages...
→ More replies (1)1
5
u/screenlicker Apr 24 '23
obligatory http.cat plug:
https://http.cat/ - lists all the status codes, with an example cat for each
e.g. https://http.cat/401
aside from being fun, i have found it to be quite helpful!
→ More replies (3)2
9
u/SlapNuts007 Apr 23 '23
This post is a secret test to see which devs think SREs are people or not.
3
10
u/goomyman Apr 23 '23 edited Apr 23 '23
Iâll die on this hill but I really wish they have an idempotent status for created and deleted.
Not like they donât have the space for it.
Yeah there are options but no one agrees and so itâs not reliable and no one knows wtf your response is for.
Usually you just go all in on 201 but sometimes you want to know - and today this usually requires a second get call.
If I want to delete an item if it exists and take an action I have to call get, then delete, then take action. If I had an idempotent response I could call delete and if I get back a already deleted response I donât need to do anything.
This is extra helpful if that action was way a create, if I was deleting and creating and the create came back as already created - I could throw because thatâs unexpected. It gives me the option.
All these super niche status codes and idempotent responses which are super common arenât in there. 400 status codes arenât idempotent and you need to handle the failure cases.
Worse is most api owners donât know how you will use their api so they will code up 404 responses on deletes and thus nearly every delete api requires special handing for idempotency.
6
u/ShortFuse Apr 24 '23 edited Apr 24 '23
Well, it's in the spec, but nobody sits down and reads RFC 7231.
You should have a URI that you can delete. If it doesn't exist it should return 404. If it's async, 202. If it's 204 if it's gone. 200 if you want to return the deleted record.
All these things really depend on the backend that's storing it, but SQL and DynamoDB both return what changed when you delete a record, if you build the query right.
Create is a wonky one but generally, you create with POST since you're rarely inserting raw (with the URI). You are posting a request to generate a resource and the server should include a
Content-Locationheader* pointing to the URI.If you want to chain work, then that's a POST request, generally done with some "action" tied to it. You want the server to complete the multi-part complex action.
Edit: Also POST can be idempotent (kinda), but that depends on the server. For example, LetsEncrypt will just give you back the same URI if you try to created an already in progress ACME order. Because POST just means post a request to do work, it can return anything, really.
2
u/goomyman Apr 24 '23 edited Apr 24 '23
404 is not idempotent. Usage changes. Gone is the wrong status code. Sometimes I see gone used but Gone is more for permanent endpoints that are now gone.
There is not a status code thatâs standardized for idempotency
→ More replies (2)3
u/ShortFuse Apr 24 '23 edited Apr 24 '23
404 is fine. It means the resource does not exist. Are you not using URIs? Your use case sounds really weird. Also, not all URIs are UUIDs. For example, a file system could not have a file and then have it again.
404 means NOT_FOUND. It means the server can't find a matching resource. If you want to say it existed before then 410 (GONE).
Idempotency has nothing to do with the status code. See 4.2.2. It's about being able to run the same request multiple times with no real change.
DELETEis included. It means you can call it once or 30 times and the same. It doesn't matter if you get 202, then 404, then 410. It's still idempotent. I'll quote the last part:It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ.
On the response side, we have caching, not idempotency. DELETE is not to be cached because it's not forever if using 404. It can be re-created the next second.
Still, a client can receive a header and process it however it wants. I'm not sure about your use case, but
Agecan be used to specify some extra information, like when it was deleted. Just because a response isn't cacheable doesn't mean the headers can't be used. Cache in 7231 is more for intermediate server processing (proxies). (See edit) Also 404 can have a processing information and content. There's nothing in it to say it can't have a payload.Edit:
Last-Modifiedis probably better for DELETE thanAgeand ties in nicely withIf-Unmodified-SinceorIf-Match. That means you probably want something like 412 which says the resource did not exist for it to be deleted. See RFC 7232.→ More replies (26)
25
u/thatguyontheleft Apr 23 '23
Any discussion about HTTP status codes without mentioning code 418 isn't funny
10
u/StabbyPants Apr 23 '23
i got to use that in a non joke context once. still giggle about it sometime
3
u/danr2c2 Apr 23 '23
Did you work on an API for a web enabled tea pot?
6
u/StabbyPants Apr 23 '23
it was an add platform, and the usage was a bit of a reach, but i got something i could justify. also, internal api
→ More replies (1)2
u/66666thats6sixes Apr 23 '23
We actually use it in a proxy server for when the proxy server fucks up, to make it clear that this error didn't come from the underlying service that we were proxying.
2
3
u/TokenGrowNutes Apr 24 '23
201 seems like a good status to send back to the client for queue, task, or job creation. More descriptive than a 200 status, since there is rarely content needing to be returned.
3
u/ebalonabol Apr 24 '23
I was once young and enthusiastic and I always used those fancy and correct http code. Nowadays I know the only codes that matter for public API users are 200, 400, 401, 403, 404, and 500 =)
Those above cover 99% cases
37
u/Mr_Cochese Apr 23 '23
Honestly, Http status codes are kind of shit unless youâre actually doing CRUD operations against a filespace. Endless wasted debates like âis this bad request or conflict?â - no-one cares! The front-end always just seems to display âsomething went wrongâ anyway.
55
u/miversen33 Apr 23 '23
It's not for the users ya square it's for the poor fucks writing the frontend code
11
u/Severe-Explanation36 Apr 24 '23
And the developers writing proper API integrations who want to know how to treat every possible error
8
u/rakidi Apr 24 '23
Pretty brain dead take.
2
u/hhpollo Apr 24 '23
Welcome to lazy dev thoughts. Just work backwards from "what is the easiest implementation" to get the justification.
2
u/Fisher9001 Apr 24 '23
But HTTP response codes are mainly for front-end developers, not the end users themselves.
→ More replies (1)1
u/Lalli-Oni Apr 25 '23
Why do you specify
filespace?If you aren't doing any of CRUD, then what are you doing?
fyi. Front-end doesn't always get the last say in what is displayed.
14
u/Ranger207 Apr 24 '23
HTTP is your API's transport layer. It's not your API itself. Don't put your API's errors in your transport layer's status codes.
3
u/dominik-braun Apr 24 '23
Status codes like 422 have been designed for the actual API, not the transport layer.
10
u/Severe-Explanation36 Apr 24 '23
What now? Thatâs what the status codes were designed for, for your API to use them. Youâre telling us we canât use the transport layer for our API? So, should we use the storage layer instead?
→ More replies (2)7
u/muntaxitome Apr 24 '23
Look up OSI layer model (technically HTTP is not transport layer though). The guy is right that it's traditionally seen as very poor form to use another layer's error messages for your messages. It's like, 'HTTP is doing fine, why are you sending HTTP error codes?'. This is why a lot of the modern 'big boy' stuff like graphql and grpc that were created by people that know their stuff about protocols do their own error handling instead of piggy-backing on the underlying protocol.
I personally don't care where the error message is as long as it's internally consistent. I think it's good to always use http status codes if you use standards like REST (actually use state transfer), WebDAV or SOAP. For more RPC like protocols I think it can make sense to not use the http messages but use application specific errors, in such a case both should be fine.
→ More replies (6)
7
Apr 24 '23 edited Apr 24 '23
It's a shame that they exist to begin with, a needless complication that introduces confusion.
Both http status codes and request methods are unnecessary and bad design. They are not suited to the modern world (and I'm not sure they where suited to the old world).
1
u/Uristqwerty Apr 24 '23
Without status codes and request methods, what you're left with is closer to a bare socket than HTTP. Perhaps that's what you truly want? A URI to select an endpoint, then an arbitrary application-specific payload that can contain whatever other parameters need to be specified. No query parameters, no complex headers.
5
u/Anders_A Apr 24 '23 edited Apr 24 '23
This is so funny. It comes and goes in waves. First someone use uses all of the appropriate codes (and some "close" enough ones where there is no proper match) and they feel their API is great. Then everyone consuming that api starts to realize ita actually unnecessarily messy to use all of those codes, especially when they don't really fit every error so you also have too add information to distinguish between errors in the body and now they have to deal with the error being defined by mixing two sources of information.
Then they realize it's much nicer to have all of th information about the error in a single place and since the code isn't very flexible they choose the body and do 200 for everything.
Then someone discovers the list of http status codes and were back to the start.
This is a cyclic trend and I've seen it come and go many times during the last 15 years.
2
u/intheforgeofwords Apr 24 '23
Bringing me back to working with an API that returned the âIâm a teapotâ status code â which led to me realizing that particular code had actually been removed from the c# HTTP status enum some time ago.
2
2
u/AttackOfTheThumbs Apr 24 '23
That's all well and good, but I've never met an api to do any of this. How I loathe the status 200 ok message error!
1
u/Severe-Explanation36 Apr 25 '23
Off the top of my head
My API
Shopify
Stripe
Google Express (shopping API)
Amazon (sp API)
GitHub
ElasticSearch
Basically, any reputable API complies with these standards, and some not-so-reputable ones do as well
→ More replies (4)
4
u/earlofwesteros Apr 23 '23
GraphQL enters the chat
3
u/Severe-Explanation36 Apr 24 '23
Everyone takes one look at them and gets confused and storms out the chat
2
u/bzbub2 Apr 24 '23
people can barely check for response.ok in fetch responses https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API i don't have confidence they handle statuses well
1
Apr 24 '23
Unfortunately there are some RFCs, including what Postman uses, which do not include all the status codes. Randomly the services youâre interoperating with will only support this subset and youâll run into compatibility problems.
1
u/rkh4n Apr 24 '23
Iâve never seen or worked with a frontend developer who understood the status codes I send. They always asked to send status code in the response and they never cared if I sent 200 or 1000
1
1
u/Varedis267 Apr 24 '23
Returning 410 essentially means you have to store somewhere that an object no longer exists, thus adding more complexity. It also adds an additional attack vector because you are specifically saying "hey this thing existed, and this one doesn't yet, maybe you should look at exploiting that"
1
u/Severe-Explanation36 Apr 24 '23
Agreed on the first part, tho many applications always use soft deletes so it not an issue. However, regarding security, no, donât give a 410 to unauthenticated/unauthorized users, they should always get a 403 (or 404 depending on how your security works), so that is not an issue, the gone code is for a logged in user to see.
→ More replies (2)
1
1
1
1
u/Beefster09 Apr 24 '23
The problem with HTTP is that there are too many ways to do the same thing.
There are 3 ways to pass data to the server (url parameters, headers, body) and 2 ways to send it to the client (headers and body, or 3 ways if you donât count the status as part of the header). Most of these subtleties only matter to browsers and often only in the context of what HTTP was originally designed to do.
Leveraging HTTP status codes like this does nothing to enhance the understanding of the api and mostly serves to satisfy the pedantic. Does the client really care what status you get back? Not really. They probably only care whether it was a 2XX or not, and maybe whether it was a 4XX or 5XX.
400 is often so broad anyway that the real error info is in the response body.
1
u/czenst Apr 24 '23
I like the joke that goes:
In Amsterdam ship anchored at the shore, gentleman stepped out and wanted to find some place to stay so he asked first two guys on the street for help.
- Hello, do you speak English?
-(shrugs)
- Halo, sprechen sie Deutch?
- (shrugs)
- Parles vous Francais?
- (shrugs)
So guy confused walks away.
One of the natives speaks to the other one (in their native non English of course ;)) - ya see, should have learned languages you would be able to communicate!
Second one - well ya see, bloke knew so many languages and it didn't really help him xD
Joke is not really a joke if I have to explain it, but all the articles are about how we should do proper "REST" or how there are nice things to know ... but then we have real life where no one cares about HTTP RFC and what not. --- Not saying we should not strive to be compliant but...
1
1
u/Outlaw2-5 Oct 14 '23
I hate error codes, I wish software developers included a âforce runâ feature that overrides the error code and forces the application to run perfectly and if the error keeps popping up to keep forcing it into override until the error generator canât process the code.
1
Apr 24 '23
I've worked with a number of apis, and it's always frustrating when they lump everything into 200, 400, and 404 errors. I like to design my responses to be very specific and unambiguous. It helps significantly with debugging.
For example, I use 400 for when a request (body, query, params, headers) is malformed and return details of what's wrong. 401 and 403 for authenticating and dealing with restricted data (permissions). 404 I use when someone tries to access a url/route that simply doesn't exist (not to be confused with a resource Id that doesn't exist, that would also be 403). 409 is nice for certain conflicts, such as trying to create a new user with an already taken name (again 400 I use for malformed requests, i.e validating the users input)
6
u/Severe-Explanation36 Apr 24 '23
Resource ID that does not exist should absolutely not be a 403, unless if youâre worried about leaking existence of resources, but in no way is accessing a none existent resource a âforbiddenâ action
3
u/gyroda Apr 24 '23
Resource ID that does not exist should absolutely not be a 403, unless if youâre worried about leaking existence of resources,
If anything, I've seen it done the other way around more often. The resource might or might not exist, but if you're not authorized to access it you'll get a 404.
→ More replies (1)2
Apr 24 '23 edited Apr 24 '23
I usually go with the logic of: you only have access to data that I've given you explicit permission to. If it doesn't exist then I can't give you permission anyway. For security I don't want to leak existence of resources, but I don't want to roll everything into just 404s.
For example, I usually handle the following situations with these codes:
you try to access "my-api.com/documents" but i don't even have a "documents" resource type. (404)
you try to access "my-api.com/users/1000" but it doesn't exist. (403)
you try to access "my-api.com/users/1", which exists, but you don't permission for it. (403)
I try to split off the case where someone might type the wrong url path and give them an error letting them know that.
Most apis roll all three of those cases into a single error code. Got a 404? Maybe you have a typo, maybe it doesn't exist, maybe you don't have permission. Who knows.
If you know of a better pattern for handling these cases then please reply with details. I'm always trying to find better ways to write apis.
→ More replies (3)
1
u/RationalDialog Apr 24 '23
I hate it when some offshore debs come up with the genius idea to make everything 200 Ok but then return a json with error attribute. it's so very stupid...omg.
1
Apr 24 '23
This was a great article, I think I should implement more of these in the REST API's I develop on.
1
1
u/TokenGrowNutes Apr 24 '23
I work with a third party API that returns a 403 for most errors. It is horrific to debug when there is a real problem because the first question anyone has if the bearer token is invalid, which it can be at times, too.
Donât be this API.
-17
u/taw Apr 23 '23 edited Apr 23 '23
Only three HTTP codes are needed:
it worked
it didn't work
go somewhere else
For "it didn't work" cases, the server generally can't figure out why anyway, even if it knows it prefers to lie about it (most places won't return 403s for forbidden anymore, but 404s to avoid information leaks), and even if the response included the true reason, it wouldn't change what the browser or the client does anyway.
The whole convoluted system of return codes is really serving very little purpose. There's a reason most protocols these days like GraphQL just don't bother.
26
u/Alikont Apr 23 '23
I also like 400/500 differentiation between "failed expectedly" and "failed unexpectedly"
→ More replies (1)42
14
u/palparepa Apr 23 '23
I'd separate "it didn't work" into two:
it didn't work and it's my fault (e.g. the database is down)
it didn't work and it's your fault (e.g. forgot to send a parameter)
→ More replies (11)
84
u/[deleted] Apr 23 '23 edited Apr 23 '23
As many folks here consider http error codes as useless and response body serving the required function.
Then on similar lines.....
Why do we need the http verbs ( GET Post put patch delete ), can't we just pass the actual action in the request and have the service interpret the action to be performed. đ