Search code examples
c#restswagger-codegen

What Status Code to use for Successful but null body?


My team and myself are trying to decide on what Status Code to use, our API Client Generated via Swagger has a condition for 204 (No Content) which has more meaning than a 404 in this instance.

We want to show that the response was successful but there was no Object returned.

Let's say it's a shopping cart: The customer clicks on the Cart and takes you to the page, the request sends to the endpoint Get//CartOrderDetails but there is no items in the cart, we don't want it to run through the API Client's 200 path, but neither do we want it to go through the 404 path since it wasn't Not Found.

What would you guys use in this case?

Edit: Thanks for all the responses overnight! Definitely helped put things in light, seems there will always be an argument for and against 204. Thanks guys!


Solution

  • What would you guys use in this case?

    we don't want it to run through the API Client's 200 path

    For REST, that's the wrong thing to want.

    Uniform interface is an important REST constraint. Among other things, that means that all resources use self descriptive messages with the same semantics.

    The status-code element is a 3-digit integer code describing the result of the server's attempt to understand and satisfy the client's corresponding request. The rest of the response message is to be interpreted in light of the semantics defined for that status code. -- RFC 7230

    In other words, the status-code is meta data of the transfer of documents over a network domain. You should be choosing the status code based on the semantics of your response message, not on how you want that message to be handled.

    If what you are sending back to the client is a representation of the resource requested, then you should be returning 200.

    If the representation of the resource happens to be zero bytes long, you might get away with sending 204 instead of 200, but that isn't really what it is for. The semantics of 204 center a corner case from remote authoring.

    Of course, if your response includes a body, then using a 204 status code is likely to make a mess; so don't do that.

    200 OK
    Content-Type: application/json
    
    null