📜 ⬆️ ⬇️

Is 200 good or bad?

In this three-minute article, I want to touch on the painful topic.

It's about the status of the HTTP 200 code and errors in the response.

HTTP/1.1 200 OK { "error": { code: 2019, message: "Validation failed: field 'size' is invalid: the value is not a number" } } 

Is it normal to return such a code if an error occurred?

Not? Yes? Well, let's see.

whaaat

Case 1. HTTP 200 and batch operation


Let's say one request is sent. The request is successful. We return the code 200. The answer does not contain information about the error. With this case, everything is extremely simple and clear. What to do if you need to perform a batch operation?


For example, we work with an image server. The provided API allows you to download multiple files in one request.

The request looks like this:

 { "sources": [ {"image": "http://myserver.com/image1.jpg"}, {"image": "http://myserver.com/image2.jpg"}, {"video": "http://myserver.com/video.jpg"} ] } 

Suppose for some reason (for example, the place on the server ran out) the video could not be loaded. What would you return in this case? 2xx or 4xx or 5xx? The server responds something like this:

 HTTP/1.1 200 OK { "results": [ { "status": "ok", "id": 312 }, { "status": "ok", "id": 313 }, { "status": "fail", "error": "NO SPACE" } ] } 

Some services (and quite well-known) act as well. 200 answer. And in the answer they return a list of commands that could not be completed.

Case 2: HTTP 200 and errors in response


The request came. Request zafeililsya. For example, we forgot to specify some field. Or the date was sent not in milliseconds, but as a string. Then you definitely do not need to return 200! But alas, no.

Somewhere on the Internet, I met projects on github and bitbucket, which are specifically designed for such cases. They are simply sewn options and patterns. You can easily integrate them into your project and, as it were, be prepared for all sorts of "drops" of requests. But there is one thing.

At such times, your code gets ugly. You tell him:

- Listen, we have one external API here. He is generally normal. Just need to carefully look at what comes in response. If there the answer contains the field "error", then the request is broken.
- But for the same there are 4xx and 5xx! Who does that at all ?!
- Hush hush. Don't be so loud. He can hear. Please be kinder to him. And just look not only at the status code, but also at the answer, please.
- Okay…

HTTP 200 is just a status.


Well, 200 and 200. Well, not gash. Or did not have time. Or not at all. So what?! Posted by json parser and all!

As if yes, but I want to know why. Forgot? Scored? Did not make it? Did not know?

Maybe I'm missing something. Or do not know. I want your opinion. Urgently All good and weekend on weekends.

Source: https://habr.com/ru/post/440382/