Search code examples
c#.netvisual-studiohttpodata

Does restful design violate command-query principle?


Does RESTful design violate the command and query segregation principle?

In our design, we have controllers that route requests to service classes.

The methods in the service classes, whether they are GET/POST/PUT, will ALWAYS have a return value:

public Dog PutDogToSleep(/*params*/)
{
   dogService.Sleep(..);
   return dog;
}

I can't find it right now, but I read that an HTTP RESTful request (get/post/put) should return the object on which you are running the request. For example, if you are doing a PUT, then you would perform that put and then return the current state of the object.

Since our methods are doing something (.Sleep) AND returning data, are they violating the command and query seg principle?

Does REST implementation not conform to command/query?

If you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.


Solution

  • Related to your commands that do something and return data, well, in a strict way of speaking that violates CQS; because commands normally don't return anything and as such can even be executed asynchronously. However, I like the more pragmatic approach: the commands can return an ID if needed.

    This ID you could then return to the consumer of your REST API; which is basically what the consumer needs to identify the created or modified entity; and what the specs say:

    "If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30)."

    Also, you can use projection to:

    • construct view-only DTO's based on your data entities for your query side
    • construct command DTO's for your command side

    ...and expose those with your REST service, this way you really control yourself what you are exposing.