0

I'm trying to learn more about REST and I was wondering about this situation:

REST Service INPUT

{ 
  nrX: "1",
  nrY: "2"
}

REST Service OUTPUT

{ 
  sum: "3"
}

If something goes wrong in the REST Service internal implementation what should we return to the client who called the rest service ?

For my project i'm always returning this:

In case of failure:

{ 
  exception: {
    description: "description of the err",
    code "500"
  }
}

In case of success:

{ 
  exception: {
    description: "",
    code "200"
  }
  response: "3"
}

is this correct ?

Stefan
  • 11
  • 3
  • 2
    Usually when you have a successful call to a REST API, you just directly get back the response object. As you already have the HTTP status code from the HTTP communication directly, you don't need to replicate it in the response payload. Reporting a `200` code in a property `exception` is misleading. For errors, it's common to have a `message` property in the body payload explaining the error. The error code itself can be left to the HTTP headers. – fjc Jun 24 '21 at 19:25
  • 1
    Also to add to what fjc said, look up what each section of HTTP responses mean so you know when to use each (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status), 4xx represent client error which is usually what you return if for example a client asks for a resource that doesnt exist so you give him 404. 5xx are Server errors, those you get when your server crashes or similar and when you get that its usually pretty bad. So avoid using 5xx for responses, if it happens you will know, stick to 4xx. – Mihsu Jun 24 '21 at 20:16
  • May be of interest: [REST API error return good practices](https://stackoverflow.com/questions/942951/rest-api-error-return-good-practices). Side note: If a question strays too far into [primarily opinion-based](https://stackoverflow.com/help/on-topic), it may be closed, as you can see. – andrewJames Jun 24 '21 at 20:18

0 Answers0