user2255299
user2255299

Reputation: 190

HTTP REST Response if dependent operation fails

Suppose a caller sends POST request to a REST server to create a resource. The server creates the resource and returns 201.

Now, the server code is modified to perform other operations if the resource is created successfully. These operations can be anything - creating another resource for bookkeeping, updating another resource, etc.

If any or all of these dependent operations fail, should the server return 201 to the caller (as the intended resource was created) OR result in failure (even though caller is not aware of / concerned about these dependent resources) ?

Upvotes: 1

Views: 946

Answers (3)

ToTheMax
ToTheMax

Reputation: 1031

When you return HTTP status 201 you should return the resource that is created in the response, if the operation failed you shouldn't return 201 in the first place.

Anyway, HTTP status codes are mostly used to check the status of the request itself, not the logics behind it. A better way is to always return a 200 when the request itself succeeded. In the response-body you can return some more info about the operations, a boolean whether the actions succeeded or not in JSON format for example.

Upvotes: 0

Evert
Evert

Reputation: 99533

The way most of the HTTP spec is written is that requests should usually either completely succeed, or completely fail.

However, some nuance can be applied to this.

If the server-state is modified, and it's intended that a HTTP request such as yours can do one or more things, I would argue that you could consider this a 'success', and you should return a 2XX response.

If I receive a 4XX response, the request should have completely failed though.

Upvotes: 0

Fellipe Sanches
Fellipe Sanches

Reputation: 8135

HTTP responses relate to a request, if successful the return will always be successful. For example, listing a table in the database that should have data, but is empty, will return successfully since the default goal was just to list the table.

You can find the definition of all response codes here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

What can be used is using a programming language to handle the return of your API by creating conditionals to return a custom HTTP response based on what you understand to be a success request or not.

Upvotes: 0

Related Questions