Home > Software engineering >  Should REST API always return response with a message?
Should REST API always return response with a message?

Time:12-05

I'm not sure whether I should include success message in the response when I create an API server.
Like when you PUT something to the API server and the backend creates something successfully, you can get a response with 201 status code.
Does the API server should include a message like:

{
  "message": "Successfully created."
}

as JSON in the response?

CodePudding user response:

Should REST API always return response with a message?

It's not required - we have 204 (No Content) and 205 (Reset Content) in the standard because there are cases where a response without a body makes sense.

But in common cases where we are sending a 200/201, I would expect to see a response body describing the status of the action

The 201 response content typically describes and links to the resource(s) created.

CodePudding user response:

I agree with VoiceOfUnreason: it not is mandatory, but I usually return

{"status":"ok"}

If I need to return some content

{"status":"ok","data":{.....}}

And, in case an error occurs, I still prefer to return a 200 handling the error at the application level

{"status":"ko","errorMessage":"Something went wrong!"}

Fabio

CodePudding user response:

No for example, for 204 responses we must not include message body. {success: true} is redundant.

In practice (or should I say in later version of jquery), empty response for application/json content type raises error. I kind of understand the argument that because it's application/json it must have a valid json body. So, empty response for application/json content type would be 'null' or '{}' which are valid json.

There's another way which should work for jquery, that is not returning application/json for empty responses. Just use text/plain or something and make sure client can handle that type.

  • Related