I prefer simplicity and using the first example but I’d be happy to hear other options. Here’s a few examples:

HTTP/1.1 403 POST /endpoint
{ "message": "Unauthorized access" }
HTTP/1.1 403 POST /endpoint
Unauthorized access (no json)
HTTP/1.1 403 POST /endpoint
{ "error": "Unauthorized access" }
HTTP/1.1 403 POST /endpoint
{
  "code": "UNAUTHORIZED",
  "message": "Unauthorized access",
}
HTTP/1.1 200 (🤡) POST /endpoint
{
  "error": true,
  "message": "Unauthorized access",
}
HTTP/1.1 403 POST /endpoint
{
  "status": 403,
  "code": "UNAUTHORIZED",
  "message": "Unauthorized access",
}

Or your own example.

  • @redline23@lemmy.world
    link
    fedilink
    58 months ago

    I like the fourth or the last one since it encourages all other error responses to follow a similar standard. That will allow the client to have a reusable error model and error checking.

    I’ve had to use APIs where every response was 200 ok with json, 400 bad request with pain text that said unauthorized, or a 500 error that returned an HTML error page. The worst.

  • vasametropolis
    link
    fedilink
    English
    7
    edit-2
    8 months ago

    1 or 4 but wrapped in a top level error object. It’s usually best to not use the top level namespace because then you can’t add meta details about the request easily later without changing the original response schema.

    Codes are great but I’m usually too lazy to introduce them right away, so I instead have message (which is guaranteed to come back) and context, which is any JSON object and doesn’t adhere to a guaranteed structure. Another poster pointed out that code is way easier for localization since you are probably not localizing your message.

    The HTTP status code is generally sufficient to describe what happened without having to catalogue every error with a unique “code”. A context blob is useful for dumping validation errors or any other details about the error that a human could at least rely on for help.

    Putting the status code on the body seems helpful but is actually useless, since the only place you can assume it’s always provided is on the response itself and not the body.

  • Hazelnoot [she/her]
    link
    fedilink
    English
    18 months ago

    Anything except the 2nd to last one, which is, unfortunately, mandated by my employer’s internal code style guidelines. 🫠

  • @elrik@lemmy.world
    link
    fedilink
    English
    188 months ago

    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?

  • @thesmokingman@programming.dev
    link
    fedilink
    28 months ago

    There are competing interests here: normal consumers and script kiddies. If I build an API that follows good design, RFCs, pretty specs, all of that, my normal users have a very good time. Since script kiddies brute force off examples from those areas, so do they. If I return 200s for everything without a response body unless authenticated and doing something legit, I can defeat a huge majority of script kiddies (really leaving denial of service). When I worked in video games and healthcare, this was a very good idea to do because an educated API consumer and a sufficiently advanced attacker both have no trouble while the very small amount of gate keeping locks out a ton of annoying traffic. Outside of these high traffic domains, normal design is usually fine unless you catch someone’s attention.

      • @thesmokingman@programming.dev
        link
        fedilink
        18 months ago

        That’s true! It also seems like you might not have experience dealing with attacks at scale? Defense in depth involves using everything. If I can reduce incoming junk traffic by 80% by masking returns, I have achieved quite a lot for very little. Don’t forget the A in the CIA triad.

  • @killabeezio@lemm.ee
    link
    fedilink
    78 months ago

    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.

  • @ShortFuse@lemmy.world
    link
    fedilink
    14
    edit-2
    8 months ago

    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.

      • lemmyvore
        link
        fedilink
        English
        48 months ago

        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.

  • @CaptPretentious@lemmy.world
    link
    fedilink
    28 months ago

    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.

  • Daemon Silverstein
    link
    fedilink
    28 months ago

    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.

  • @kevincox@lemmy.ml
    link
    fedilink
    68 months ago
    HTTP/1.1 403 UNAUTHORIZED
    {
      "error": {
        "status": "UNAUTHORIZED",
        "message": "Unauthorized access",
      },
    }
    

    I would separate the status from the HTTP status.

    1. The HTTP status is great for reasonable default behaviours from clients.
    2. 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.

  • asudox
    link
    fedilink
    4
    edit-2
    8 months ago

    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?

    • @FourPacketsOfPeanuts@lemmy.world
      link
      fedilink
      4
      edit-2
      8 months ago

      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

  • @SorteKanin@feddit.dk
    link
    fedilink
    28 months ago

    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.

    • Kogasa
      link
      fedilink
      58 months ago

      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.

      • @SorteKanin@feddit.dk
        link
        fedilink
        18 months ago

        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.

        • @b_n@sh.itjust.works
          link
          fedilink
          18 months ago

          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.

          • @SorteKanin@feddit.dk
            link
            fedilink
            28 months ago

            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.