Should CQRS services be RESTful?

4,603 views
Skip to first unread message

Naresh Bhatia

unread,
Sep 19, 2011, 1:58:27 AM9/19/11
to ddd...@googlegroups.com
When designing a service that responds to commands or queries, do you think making it RESTful is beneficial? In some ways I think that CQRS and REST are conflicting paradigms. REST fully exposes resources to the client - resources that can be created, updated and deleted. On the other hand CQRS hides the resources (entities) behind commands - they can be changed only by issuing very specific commands.

Thoughts / comments?

Philip Jander

unread,
Sep 19, 2011, 3:56:29 AM9/19/11
to ddd...@googlegroups.com

There was a talk on REST+CQRS at DDDX 2011, see skillsmatter.com for
video. Admittedly the speaker just scratched the surface of these questions.

I'd say you are correct in that you wouldn't expose your domain model.

You would PUT new commands, maybe GET the status of pending commands,
DELETE pending commands, GET parts of the readmodel (aka query).
In addition you would probably POST to subscribe to new events (not
necessarily "events" as in "event sourcing" but rather application
events and notifications of changes to the readmodel).

Hence the resources are the available commands and queries and available
event publishers. Those can be advertised as part of a RESTful services
resonse.

Cheers,
Phil

Sharas

unread,
Sep 19, 2011, 4:22:34 AM9/19/11
to ddd...@googlegroups.com
You expose resource representations as you would expose your applications API that accepts commands. Nothing wrong with that. Below resource representations there is your applications state machine and business rules which are encapsulated.

Rickard Öberg

unread,
Sep 19, 2011, 4:37:48 AM9/19/11
to ddd...@googlegroups.com

The main problem with REST is that most of the article authors/bloggers
suggest that you should expose your domain model, which is insane. If
you instead expose your usecases, i.e. commands and queries, as
resources which can be manipulated with representations, it's all good.
Works like a charm. Main problem is that there is no decent framework,
yet, that makes this easy to do. Working on that...

/Rickard

John Thornborrow

unread,
Sep 19, 2011, 6:12:33 AM9/19/11
to ddd...@googlegroups.com
I think PUTting commands is missing a beat with REST.

Instead of:

==
PUT /command
content-type = application/json; charset=utf-8

{"command" : { /* some json describing the command */ }}
==

The verbs afforded to HTTP should form part of the command, in my opinion. For example the user issues a UpdateCustomerAddress command.. surely that should be:

==
POST /customer/<customer id>/address
Content-Type: application/json; charset=utf-8

{"customerAddress":"etc"}
==

Or they issue a DeleteNoteFromOrder command:

==
DELETE /order/<order id>/note/<note id>

<no content needed.. the command is the http-request.>
==

etc.

J.

Philip Jander

unread,
Sep 19, 2011, 6:36:25 AM9/19/11
to ddd...@googlegroups.com

I think PUTting commands is missing a beat with REST.

I beg to differ ;)

That kind of API brings us right back into CRUD-space, and thus away from DDD.


==
POST /customer/<id>/address 
==

carries no information on why that address was changed.

==
PUT /customer/<id>/commands
Content-Type: application/json; charset=utf-8
Id: <commandid>

CustomerMovedCommand { Movedto:<newaddress> }
==
does so.
Now, you could generate new http verbs for each command in order to transport the intent.
E.g.
==
MovedTo /customer/<id>
Content-Type: application/json; charset=utf-8
Id: <commandid>

{ Address:<newaddress> }
==

This, however, leads to an RPC style API. See the cited talk by Jim Webber at DDDX for a brief discussion of using the standard four http verbs versus extending http.

The charm of CQRS is that messages (commands) are encapsulated in objects capable of carrying meta information and being processed (e.g. passed along dynamically configured command handler chains).

Cheers
Phil

Damon Stephenson

unread,
Sep 19, 2011, 7:00:23 AM9/19/11
to ddd...@googlegroups.com
Personally, I suggest inferring meaning from a POST request or even a PATCH request using another resource. Also, using the query string can be useful too.

POST /customer/<id>/move/
{ "address": "The Moon" }

John Thornborrow

unread,
Sep 19, 2011, 7:05:51 AM9/19/11
to ddd...@googlegroups.com
On Mon, Sep 19, 2011 at 11:36 AM, Philip Jander <jan...@janso.de> wrote:

I think PUTting commands is missing a beat with REST.

 
  I beg to differ ;)  
That kind of API brings us right back into CRUD-space, and thus away from DDD.

No it doesn't. Well, only if you let/want it to.. I don't see anything CRUD about my examples.  I'm still issuing commands, but I'm actually using a service for what it was designed for. If all you are doing is PUTting commands, you are simply creating a protocol within a protocol. I.e. here's a put request with a serialised command. Instead you could have a request that *is* the command. 

Why add that extra layer of complexity when the protocol you are already using (HTTP) encompasses and encapsulates what you want to do? 


== 
POST /customer/<id>/address 
==

carries no information on why that address was changed.
Sure it does.. just add a "reason" field to the POSTed data and there is your reason. It's a command, not an aggregate/entity after all..

==
PUT /customer/<id>/commands
Content-Type: application/json; charset=utf-8
Id: <commandid> CustomerMovedCommand { Movedto:<newaddress> } ==
  does so.

*THAT* is RPC. Also, if you break down the request, you are doing two operations in one. Get me the customer with ID, and then issue this command to them. That's not CQRS, imo. That's CRUD-space. I'm going to assume though that you meant for the customer ID to be within the command, not in the URI. :)
 
Now, you could generate new http verbs for each command in order to transport the intent.
E.g.
==
MovedTo /customer/<id>
Content-Type: application/json; charset=utf-8
Id: <commandid> { Address:<newaddress> } ==

This, however, leads to an RPC style API. See the cited talk by Jim Webber at DDDX for a brief discussion of using the standard four http verbs versus extending http.

The charm of CQRS is that messages (commands) are encapsulated in objects capable of carrying meta information and being processed (e.g. passed along dynamically configured command handler chains).

Cheers
Phil

I *never* advocate extending HTTP verbs (of which there are 9 standard verbs, not 4, fyi). As said before, my examples are still commands. I don't see where this assumption they are not commands has come from. Probably because this is a perfect example of the biggest misconception of REST to ever exist.

Rickard Öberg

unread,
Sep 19, 2011, 7:11:09 AM9/19/11
to ddd...@googlegroups.com
On 9/19/11 12:36 , Philip Jander wrote:
>
>> I think PUTting commands is missing a beat with REST.
>
> I beg to differ ;)
>
> That kind of API brings us right back into CRUD-space, and thus away
> from DDD.

Agree. It's an anti-pattern to expose domain models like that.

> ==
> POST /customer/<id>/address
> ==
>
> carries no information on why that address was changed.
>
>
> ==
> PUT /customer/<id>/commands
> Content-Type: application/json; charset=utf-8
> Id:<commandid>
>
> CustomerMovedCommand { Movedto:<newaddress> }
> ==
>
> does so.
> Now, you could generate new http verbs for each command in order to
> transport the intent.

I prefer creating resources for commands and queries, e.g.:
GET /<usecasename>/<id>/
-> links to valid commands, e.g.
GET /<usecasename>/<id>/updateaddress
-> form for updating address
POST/PUT /<usecasename>/<id>/updateaddress
-> list of events caused by command, or error

I.e. commands and queries are made into explicit resources, supporting
as many verbs as makes sense. This makes it really easy to do UI's,
since by checking the list of links in the GET on ../<id>/ you can
determine what buttons or other UI fields should be enabled. If, for
example, the current user is not allowed to change the address, or the
connection to the underlying LDAP server is down, then the link to
"updateaddress" is missing, and the UI can react accordingly (disable
buttons/fields, or hide them entirely).

To determine whether to use POST or PUT on /updateaddress I add a class
"idempotent" on the link, but you can also use the "Allow" header in the
GET call to determine this.

I put "<usecasename>" in the above, because the URL should reflect the
usecase and not the domain model. "customer" is not a usecase,
typically. Replace with whatever makes sense in your domain.

/Rickard

John Thornborrow

unread,
Sep 19, 2011, 7:27:43 AM9/19/11
to ddd...@googlegroups.com
"POST customer/<customer id>/address"

There's the use case name.. you're posting the customer's address. How can you not see that? :)

Rickard Öberg

unread,
Sep 19, 2011, 7:34:30 AM9/19/11
to ddd...@googlegroups.com
On 9/19/11 13:27 , John Thornborrow wrote:
> "POST customer/<customer id>/address"
>
> There's the use case name.. you're posting the customer's address. How
> can you /not/ see that? :)

Because having a usecase called "customer" is really really weird. That
sounds like a domain name, and not a usecase name, is what I mean.

I can compare with the problem I ran into in my own app. I used to have
this:
/user/rickard/

from which I could do two commands: changepassword and resetpassword.
But that becomes REALLY funky when you try to do authorization and
linking properly, since they are part of two different client usecases.
So instead I changed this to:
/account/ (my own user is implied)
/administration/server/user/rickard/

i.e. the usecases are "account management" and "user administration",
with changepassword and resetpassword respecticaly. With that change it
became much more easy to handle, on the server and client. So, again,
"customer" to me doesn't sound like a usecase. It sounds like exposing
the domain model, and that breaks down fantastically when you try to do
HATEOAS properly.

/Rickard

John Thornborrow

unread,
Sep 19, 2011, 7:38:51 AM9/19/11
to ddd...@googlegroups.com
You've mis-understood. "customer" isn't the usecase name. "POST /customer/<cust id>/address" is the usecase name. 

Rickard Öberg

unread,
Sep 19, 2011, 7:45:19 AM9/19/11
to ddd...@googlegroups.com
On 9/19/11 13:38 , John Thornborrow wrote:
> You've mis-understood. "customer" isn't the usecase name. "POST
> /customer/<cust id>/address" is the usecase name.

Again, that's a terrible usecase name, because that is "what the system
is", whereas usecase names should reflect "what the system does". Good
luck creating sensible links that guides the user agent to perform
application state transitions.

/Rickard

John Thornborrow

unread,
Sep 19, 2011, 9:10:34 AM9/19/11
to ddd...@googlegroups.com
You make it what you want it to be.

"POST /customer/<cust id>/changeAddressTo"

In short: use the HTTP methods (aka verbs) for what they are intended to be used for, don't cop out and just PUT commands to a generic "/commands" end point is all I'm saying. :)

Kevin Swiber

unread,
Sep 19, 2011, 11:20:12 AM9/19/11
to ddd...@googlegroups.com
On Mon, Sep 19, 2011 at 1:58 AM, Naresh Bhatia <naresh.a...@gmail.com> wrote:
When designing a service that responds to commands or queries, do you think making it RESTful is beneficial? In some ways I think that CQRS and REST are conflicting paradigms. REST fully exposes resources to the client - resources that can be created, updated and deleted. On the other hand CQRS hides the resources (entities) behind commands - they can be changed only by issuing very specific commands.

Thoughts / comments?

There's some discussion around this on the Design of Distributed Applications group[1].

Here are some thoughts I have about this.  In my free time, I've been working on an example app to demonstrate.

Your Domain Model is _not_ your Application Model.  CQRS deals with sending commands to and firing events from your Domain Model.  REST exposes resource representations of your Application Model.  A clear separation allows them both to evolve independent of each other.

In the classic "New Customer"example, here's the order of operations at the moment the client makes the request:

1. Client sends an HTTP request to a REST application service (i.e., POST /customers/) with a request body containing the necessary fields and values.
2. REST application service receives the request and generates a CreateNewCustomer command that it sends through the command bus.
    a. Optionally, the REST service returns 202 Accepted to the client, assuming all went well.  You could also return an optimistic 201 Created with the new customer's hypermedia.
3. The CreateNewCustomer command is consumed, and a NewCustomerCreated event gets published.

GET requests (queries) work similarly.

1. Client sends a GET /customers/1234
2. REST application sends a query through a thin DTO layer.
3. REST application sends a 200 OK with the customer hypermedia.

The Design of Distributed Applications group was, in part, created to discuss topics such as this, as it is somewhat OT to either a CQRS or REST group.  That may be a better place to have this conversation.

[1] http://groups.google.com/group/the-design-of-distributed-applications

Hope that helps.  A lot of folks, including myself, are still working to map out the best of both worlds.

--
Kevin Swiber
Projects: https://github.com/kevinswiber
Twitter: @kevinswiber

David Findley

unread,
Sep 19, 2011, 11:43:19 AM9/19/11
to ddd...@googlegroups.com
I agree. The only time I would consider using PUT is to issue a command that creates an entity:

PUT /customer/1
{ "Name": "Bob" }

I would then use POST commands with the command name in the url:

POST /customer/1/changename
{ "Name": "Robert" }

I am currently looking at implementing something like this using the WCF Web API. I think I can write it in a generic way where I can just map the command name to a class that implements IHandle<ChangeNameCommand> or using an attribute like [Handles("changename")].

Kevin Swiber

unread,
Sep 19, 2011, 11:56:52 AM9/19/11
to ddd...@googlegroups.com
On Mon, Sep 19, 2011 at 3:56 AM, Philip Jander <jan...@janso.de> wrote:
You would PUT new commands, maybe GET the status of pending commands, DELETE pending commands, GET parts of the readmodel (aka query).
In addition you would probably POST to subscribe to new events (not necessarily "events" as in "event sourcing" but rather application events and notifications of changes to the readmodel).

Hence the resources are the available commands and queries and available event publishers. Those can be advertised as part of a RESTful services resonse.


I'd like to see the presentation you mention.  In my opinion, it sounds like the REST client in this scenario should _not_ be a user-agent that exposes information or commands to an end user (flesh-and-blood human being).

This sounds like a REST API over a business integration server.  I can see multiple applications communicating with this API to plug in to the Domain Model.

Naresh Bhatia

unread,
Sep 19, 2011, 12:54:23 PM9/19/11
to ddd...@googlegroups.com
Reading this thread so far, it is clear that there is no single right way to implement CQRS based services. What is interesting to me is that many responses automatically assume that it should be done the RESTful way and then moving on to the how.

Can we step back and discuss why not maintain the concept of Commands and Queries as first-class citizens all the way to the client? (Let's call this approach "CQRS-All-The-Way"). After all we have spent so much of our precious time crafting commands and queries and making sure they mean something in our domain. Instead of translating them into GETs and POSTs, why not expose them directly to the client? (Note that I am intentionally not using the term RPC because I feel that a Command is not a remote procedure call.) In other words, I don't see much difference between

POST /customer/1/changename
{ "Name": "Robert" }

and posting the following command to a CustomerService

{
    command: "changeName",
    id: "1",
    newName: "Robert"
}

except they use different mental models. However, I do see the some distinct advantages of going "CQRS-All-The-Way":
  • The concept of commands and queries is kept intact all the way to the client.
  • There is no translation necessary on the client or the server (in the RESTful way, one needs to interpret a URL and convert it to a command or a query that is understood by the domain).
  • It works even if we change the transport layer to something else (e.g. a message service).
  • We can collect bunch of commands at the client and send them as a single transaction to the server.
Again, I am not religious about either approach - both get the job done. Just wondering if anybody has considered or implemented approach 2, i.e. "CQRS-All-The-Way".

Thanks for your input.

Naresh


Rickard Öberg

unread,
Sep 19, 2011, 1:32:23 PM9/19/11
to ddd...@googlegroups.com
On 9/19/11 18:54 , Naresh Bhatia wrote:
> In other words, I don't see much
> difference between
>
> POST /customer/1/changename
> { "Name": "Robert" }
>
> and posting the following command to a CustomerService
>
> {
> command: "changeName",
> id: "1",
> newName: "Robert"
> }
>
> except they use different mental models.

To me there is a big difference here. First of all, I can create a link
to the first, but no to the second, thus informing the client about the
possible next states. Also, I can do a GET on the first and either get
200 (=it's ok to perform the command) or 404 (=it's not ok to perform
the command), which is very important from a UI point of view. Never
allow UI's to "try" commands that are sure to fail. The first variant
helps, whereas the second don't.

/Rickard

David Findley

unread,
Sep 19, 2011, 2:15:29 PM9/19/11
to ddd...@googlegroups.com
What is wrong with exposing my domain model's aggregate roots as resources over http? The client can still think of things as "commands" since they have to pass the command name as part of the url and as Rickard says there will be a uri that represents that aggregate root now. Maybe it could be more clear to use a query string parameter?

POST /customer/1?command=changeName
{ "Name": "Robert" }

Putting the command name in the message body makes the command message feel like an RPC call representation to me. It probably doesn't really matter that much.  At the end of the day it really is an RPC call. Its a message that results in invoking a method on a command handler.

David Findley

unread,
Sep 19, 2011, 2:25:38 PM9/19/11
to ddd...@googlegroups.com
I think it also depends on your clients. Using REST inherently ties you to the http protocol. But it seems to me that more and more folks are embracing the simplicity of the http protocol these days and ditching more complex frameworks like WCF. I may just be reading the wrong set of blogs. It is easy to get caught in an echo chamber these days. :O

Naresh Bhatia

unread,
Sep 19, 2011, 5:05:58 PM9/19/11
to ddd...@googlegroups.com
On Mon, Sep 19, 2011 at 2:15 PM, David Findley <xpa...@gmail.com> wrote:
What is wrong with exposing my domain model's aggregate roots as resources over http? The client can still think of things as "commands" since they have to pass the command name as part of the url and as Rickard says there will be a uri that represents that aggregate root now. Maybe it could be more clear to use a query string parameter?

POST /customer/1?command=changeName
{ "Name": "Robert" }

This approach looks much cleaner to me and maintains the spirit of a command. I like it!

Thanks for sharing.

Naresh

 

Philip Jander

unread,
Sep 20, 2011, 4:35:05 AM9/20/11
to ddd...@googlegroups.com
Am 19.09.2011 15:10, schrieb John Thornborrow:
> You make it what you want it to be.
>
> "POST /customer/<cust id>/changeAddressTo"
>
> In short: use the HTTP methods (aka verbs) for what they are intended
> to be used for, don't cop out and just PUT commands to a generic
> "/commands" end point is all I'm saying. :)
>
I agree. The initial POST .../address was too close to crud so I did not
get your intention upthread.
If I advertise commands as resources, they should be available as
resouces, so it is customer/<id>/MoveToNewAddress or
.../NameChangeDueToMarriage if the domain requires such a level.

Still, there is a subtle difference in "changeAddressTo" and
"MoveToNewAddress", but whether this difference is important depends on
the business case.

There is some debate as to whether to POST or PUT commands.
I think I would prefer PUT /customer/<id>/MoveToNewAddress/<cmdid> where
the cmdid is defined by the sender
This way, sending the command is idempotent.

Cheers,
Phil

Rickard Öberg

unread,
Sep 20, 2011, 5:44:47 AM9/20/11
to ddd...@googlegroups.com
On 9/19/11 20:15 , David Findley wrote:
> What is wrong with exposing my domain model's aggregate roots as
> resources over http?

Everything. Unfortunately that model is what almost all bloggers
suggest, which is causing a mess beyond belief.

Let's start with this: how do you create links in the hypermedia to
guide the client to achieve state transitions that are ok according to
the application usecases? (This is what the REST thesis says that you
should do, so this is mandatory)

/Rickard

John Thornborrow

unread,
Sep 20, 2011, 5:59:27 AM9/20/11
to ddd...@googlegroups.com
re: PUT vs POST; I usually go with the PUT is adding a new aggregate (i.e. synonymous with Create) and POST is update an existing aggregate (i.e. synonymous with Update).

Yes, that is incredibly CRUD of me, but I've found it works. :)

I think my other point is also that I don't consider commands to be first class. I only consider them to be communications (or, to be more exact, instructions) from client to domain, thus my gut tells me it is wrong to PUT commands because I can't "create" a command, because a command never actually "exists". :)

Others may/will disagree :)

J.

Sharas

unread,
Sep 20, 2011, 6:02:20 AM9/20/11
to ddd...@googlegroups.com
Agreed, although I wouldn't treat Fieldings thesis a as a mandatory prescription:) People are talking about REST maturity levels our days:)

When implementing apps in a RESTfull manner you expose business capabilities or application protocol with your resource representations sprinkled with hypermedia controls.
That means you are guiding your client and suggesting possible valid transitions with each step client performs.

This gives opportunities to extend your application protocol without changing your domain model. Which you would have to do if you expose your aggregate roots as Rickard suggest. E.G. you can add a possibility for clients to complete a survey for a discount without changing your existing model. And you do it unobtrusively, clients that know how to use that capability will use it without breaking old clients. 

How about reading couple of books about REST before discussing whether to apply it without knowing what it is and what it's for:

Rickard Öberg

unread,
Sep 20, 2011, 6:02:15 AM9/20/11
to ddd...@googlegroups.com
On 9/20/11 11:59 , John Thornborrow wrote:
> re: PUT vs POST; I usually go with the PUT is adding a new aggregate
> (i.e. synonymous with Create) and POST is update an existing aggregate
> (i.e. synonymous with Update).
>
> Yes, that is incredibly CRUD of me, but I've found it works. :)
>
> I think my other point is also that I don't consider commands to be
> first class. I only consider them to be communications (or, to be more
> exact, instructions) from client to domain, thus my gut tells me it is
> wrong to PUT commands because I can't "create" a command, because a
> command never actually "exists". :)
>
> Others may/will disagree :)

How do you use hypermedia to allow client to find out what commands are
available and how to invoke them?

/Rickard

Rickard Öberg

unread,
Sep 20, 2011, 6:13:49 AM9/20/11
to ddd...@googlegroups.com
On 9/20/11 12:02 , Sharas wrote:
> Agreed, although I wouldn't treat Fieldings thesis a as a mandatory
> prescription:) People are talking about REST maturity levels our days:)

That's not true. It *is* a mandatory prescription. "If you apply these
constraints, you get these results". I.e., if you don't apply the
constraints, you don't get the results. You get a "Web API", which could
be JUST FINE, but it's not REST. With the Maturity Levels you need to
note that it is only at Level 3 that you get REST. The other levels are
"Web APIs", or "HTTP APIs", or whatever you want to call them. Which is
FINE, if that is what you want.

> When implementing apps in a RESTfull manner you expose business
> capabilities or application protocol with your resource representations
> sprinkled with hypermedia controls.
> That means you are guiding your client and suggesting possible valid
> transitions with each step client performs.

Yup.

> This gives opportunities to extend your application protocol without
> changing your domain model. Which you would have to do if you expose
> your aggregate roots as Rickard suggest. E.G. you can add a possibility
> for clients to complete a survey for a discount without changing your
> existing model. And you do it unobtrusively, clients that know how to
> use that capability will use it without breaking old clients.

My experience is much simpler than that: if you expose the domain model
there is no way to guide the client, since there is no "path" to be
followed. If you expose usecases, there is a guide, and doing the
linking thing becomes trivial. And writing clients becomes REALLY easy!

I would also suggest the REST thesis itself. Skip to ch5 if you are
short on time:
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

I started my project doing the "expose your domain model" thing. It was
VERY painful. The more I changed to what Roy is talking about, the
simpler my server and client became. Stop thinking about a REST API as a
"service facade", and instead think of it as a simplistic website, and
it becomes much easier to get it right.

/Rickard

Udi Dahan

unread,
Sep 21, 2011, 6:16:44 AM9/21/11
to DDD/CQRS
Following Rickard's statements:

> if you expose the domain model there is no way to guide the client, since there is no "path" to be
> followed. If you expose usecases, there is a guide, and doing the linking thing becomes trivial.

In which case, the resources are aligned with use cases / commands.
If you have AR's that aren't aligned with use cases / commands - then
they would be a poor choice for your resources.

Cheers,

Udi
> >http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596...
> >http://www.amazon.com/REST-Practice-Hypermedia-Systems-Architecture/d...

John Thornborrow

unread,
Sep 21, 2011, 6:38:51 AM9/21/11
to ddd...@googlegroups.com
In the same way you present any endpoint to the client. In my examples, the commands are the endpoints and methods. :)

J.

Sharas

unread,
Sep 21, 2011, 6:40:58 AM9/21/11
to ddd...@googlegroups.com
@Udi: I don't think aggregates necessary map to resources 1-1. Resources are to be manipulated with uniform interface and doesn't translate directly to expressive domain objects. There is a kinda of impedance mismatch between design for networking (resources) and object oriented models.
Manipulation of several resources can map to same AR, no? So I don't really see how AR can be mapped to resource directly.

What am I missing? 

Naresh Bhatia

unread,
Sep 21, 2011, 11:53:38 AM9/21/11
to ddd...@googlegroups.com
Udi,

A concrete example will help tremendously. I have been following this thread and trying to convert my command/query style web service to REST, but getting completely confused with conflicting opinions. Here's the web service I am trying to convert: http://archfirst.org/books/trading-service - its a retail trading service. Here's my attempt at translating one command. It is currently sort of {AR}/command. I don't quite understand how and why to make them {use case}/command - all REST literature seems to suggest exposing resources and in my use case a BrokerageAccount seems to be a good resource - it just happens to be my AR too.

Command
long OpenNewBrokerageAccount(string AccountName)

REST Translation
POST /brokerageAccount?command=create HTTP/1.1
{
    "name": "Brokerage Account 1"
}

Response
--------
200, "OK"
{
    "id": "14",
}

I could have used a PUT by supplying a UUID, but decided against it as the backed is already built and likes to assign ids. (also don't want to do a separate round trip to get an id). I could also include a link in the response to the newly created resource. Anyway, those are just details - my basic questions still remain on how to structure the request.

Thanks.

Naresh

Chris Nicola

unread,
Sep 21, 2011, 1:17:49 PM9/21/11
to ddd...@googlegroups.com
You would only PUT commands if the client completely controls the command.  My preference is not to expose the CQRS-ness of the system to the API consumer.  Instead just focus on providing a quality REST API experience.  

I feel that typically domain behaviors (use cases) will end up being exposed via resources using POST /account/{id}/begin-transaction which will likely trigger the server to create and execute a command for the client, possibly directing the user via response to a command status resource, or possibly directly to the affected resource for highly consistent operations.

Again you have a lot of choices here.  You could definitely design a REST API that is about PUTing commands, but I think that is often going to be a PITA for the client to have to implement. 

Just some thoughts.

Naresh Bhatia

unread,
Sep 21, 2011, 1:49:42 PM9/21/11
to ddd...@googlegroups.com
I agree. So I am not trying to PUT commands, just trying to come up with a good REST design. Based on your comments would the following structure be better:

POST /brokerageAccount
{
    "name": "Brokerage Account 1"
}

Response
--------
201, "Created"
{
    "id": "14"
}

Now to place an order in this account

POST /brokerageAccount/14/order
{
"symbol": "AAPL",
"side": "Buy",
"quantity": 1000
}

Response
--------
201, "Created"
{
    "id": "1212"
}

Now to change the quantity in the order, I can think of two options:

PUT /order/1212/quantity
{
"quantity": 2000
}

But this feels like I am exposing the Order entity. Another option:

POST /order/1212/changeQuantity
{
"quantity": 2000
}

This feels more like I am issuing a command.

Note also that in my domain, a quantity change has to go through the AR, i.e. the account, because only the account knows if there is enough cash to increase the quantity. However, for the REST API, it feel exposing the Order as a resource makes more sense. The implementation can worry about constructing the proper command for the AR.

Thoughts? It would be more helpful if you could respond with concrete changes to these structures to reflect your opinions.

Thanks.
Naresh



Sharas

unread,
Sep 21, 2011, 2:00:30 PM9/21/11
to ddd...@googlegroups.com
From your service description it seems that there are at least 3 resources: Orders, Accounts, Transactions. 

Example: To create an order POST to Orders resource representation of an order. Respond with 201 cretaed with location header which contains order URI with order ID.
To delete an order client sends DELETE to order URI
To update an order clients PUTS new order representation to order URI.

Sharas

unread,
Sep 21, 2011, 2:01:28 PM9/21/11
to ddd...@googlegroups.com
Correction, not delete an order but cancel an order

Naresh Bhatia

unread,
Sep 21, 2011, 2:21:53 PM9/21/11
to ddd...@googlegroups.com
All sounds good, except for the update. As far as I can tell, CQRS does not recommend a blanket update. What does it mean to change every element of an order, e.g. from

{
"symbol": "AAPL",
"side": "Buy",
"quantity": 1000
}

to

{
"symbol": "GOOG",
"side": "Sell",
"quantity": 2000
}

However, a command like changeQuantity does make sense. That's the concept I was trying to incorporate by PUTing quantity or POSTING a changeQuantity to the Order. I hope at least my question makes sense.

Naresh

Sarunas Mazylis

unread,
Sep 21, 2011, 2:44:39 PM9/21/11
to ddd...@googlegroups.com
There's a PATCH verb. Or you can specify possible transitions of an order when you respond to initial post. eg <link rel="quantity" href="https://www.xxx.com/order/123/quantity">. Client can post to quantity to update it. But now you are introducing your custom media format in effect.

Marco Heimeshoff

unread,
Sep 21, 2011, 3:39:46 PM9/21/11
to ddd...@googlegroups.com
Hi Naresh,

You should never design commands to return any value besides ack/nack. This separation is the whole point of cqrs (command&query seperation) :-) 

There are a few ways to avoid a roundtrip, one for example would be, to precreate ids and have them in the readmodel to get taken, this way you can even make sure, that between multiple clients a increasing value of invoicenumbers is keeping integrity.

Ciao,
Marco

Naresh Bhatia <bha...@comcast.net> hat geschrieben:

Udi,

A concrete example will help tremendously. I have been following this thread and trying to convert my command/query style web service to REST, but getting completely confused with conflicting opinions. Here's the web service I am trying to convert: http://archfirst.org/books/trading-service - its a retail trading service. Here's my attempt at translating one command. It is currently sort of {AR}/command. I don't quite understand how and why to make them {use case}/command - all REST literature seems to suggest exposing resources and in my use case a BrokerageAccount seems to be a good resource - it just happens to be my AR too.

Command
long OpenNewBrokerageAccount(string AccountName)

REST Translation
POST /brokerageAccount?command=create HTTP/1.1
{
    "name": "Brokerage Account 1"
}

Response
--------
200, "OK"
{
    "id": "14",
}

I could have used a PUT by supplying a UUID, but decided against it as the backed is already built and likes to assign ids. (also don't want to do a separate round trip to get an id). I could also include a link in the response to the newly created resource. Anyway, those are just details - my basic questions still remain on how to structure the request.

Thanks.

Naresh

Naresh Bhatia

unread,
Sep 21, 2011, 3:46:16 PM9/21/11
to ddd...@googlegroups.com
Yep. Very much aware of that! Just trying to retrofit into how the existing system works.

Rickard Öberg

unread,
Sep 22, 2011, 4:23:49 AM9/22/11
to ddd...@googlegroups.com

The point I'm trying to make is that exposing these domain level objects
as REST resources is the wrong thing to do. Expose usecases.

Now, I have NO IDEA what your usecases are, and quite possibly you don't
know it either (remarkably common problem), but let me just guess what
could be usecases for orders:
1) Placing an Order in a shop
2) Servicing an Order in a warehouse
3) Tracking your own Orders online
4) Displaying customers Orders in a callcenter
5) Performing analytics of Orders
etc.

All these are separate usecases, all of which require *SEPARATE* REST
API's. If you expose your domain model, which pretty much all bloggers
suggest and which pretty much all responses in this thread suggest, you
are in for massive amounts of pain when real life hits you in the butt.
You will have no way to guide the clients through the above usecases by
means of following links, and in effect all the usecase logic will be in
various client code, with lots of if statements and whatnot. I've seen
this before, and headache follows, always.

Based on the responses so far I seriously doubt that many here have
actually read the REST thesis, and I seriously doubt that many here have
actually built REST API's based on the suggestions posed, because the
pain involved with the results of said suggestions are just too obvious,
in real life.

To know what your usecases are requires understanding the UI more than
understanding the domain model. When you understand the UI, and the
usecases it contains, then you create your REST API from there, and then
map that to the underlying domain model. Not the other way round.

Then everything becomes simple, logical, and having many clients to the
same app is trivial rather than cumbersome.

/Rickard

Daniel Yokomizo

unread,
Sep 22, 2011, 8:58:48 AM9/22/11
to ddd...@googlegroups.com

I actually tried to do the AR as resources thing. It was  very bad because we had to embed many UI rules in the domain and there was no easy way to not break (heavily) the UI when we refactored the domain. In REST you sometimes need resoures coarser than your domain entities, not having these and relying on object navigation forces your domain to be anemic and data-structure oriented. Having resources too fine grained makes your API  too chatty which is very bad in  REST.

Rickard Öberg

unread,
Sep 22, 2011, 9:27:32 AM9/22/11
to ddd...@googlegroups.com
On 9/22/11 14:58 , Daniel Yokomizo wrote:
> I actually tried to do the AR as resources thing. It was very bad
> because we had to embed many UI rules in the domain and there was no
> easy way to not break (heavily) the UI when we refactored the domain.

Exactly. You need the usecases as the mediator between the UI and the
domain, and when you expose the domain you either have to put usecases
in the domain (which doesn't work), or you have to put the usecases in
the UI, which leads to chatty and inconsistent usecase handling.

> In
> REST you sometimes need resoures coarser than your domain entities, not
> having these and relying on object navigation forces your domain to be
> anemic and data-structure oriented.

Exactly. The usecases provides that middle ground that does this, and in
a consistent way no matter which client uses it.

> Having resources too fine grained
> makes your API too chatty which is very bad in REST.

Exactly. I have seen cases where one UI screen makes hundreds of REST
calls, to get attributes from various domain objects. It is ok on a dev
machine (localhost access), but not so ok in a real production
environment. Both latency and scalability goes down the drain.

And these are all things that I have seen in my own and others'
projects, every time, which leads me to question whether the other
respondents in this thread has actually 1) read the REST thesis and 2)
tried this in real life. Same goes for bloggers who suggest that
exposing the domain model is a good way to do REST.

The hardest part about exposing usecases is that you have to actually
know what they are. But that's a GOOD problem, and finding that out is
in line with DDD in general, and understanding the business problems as
well.

/Rickard

Simon Harris

unread,
Sep 22, 2011, 9:36:26 AM9/22/11
to ddd...@googlegroups.com
This is, IMHO, one of the best paragraphs on REST:

"Web architects must understand that resources are just consistent mappings from an identifier to some set of views on server-side state. If one view doesn’t suit your needs, then feel free to create a different resource that provides a better view (for any definition of “better”). These views need not have anything to do with how the information is stored on the server, or even what kind of state it ultimately reflects. It just needs to be understandable (and actionable) by the recipient."

http://roy.gbiv.com/untangled/2008/paper-tigers-and-hidden-dragons

Philip Jander

unread,
Sep 22, 2011, 11:02:30 AM9/22/11
to ddd...@googlegroups.com

This is sort of contrary to the CQRS + DDD ideas. As many have already
stated, you should *not* expose your domain entities as resources. Make
up are API based on commands and queries which result from your business
case, not your mental domain model.
Talk to your business, define user cases and use DDD. Or else, if the
problem domain is shallow enough, forget about DDD and CQRS altogether.
For many applications, this is just too heavy a toolset.

Phil


Rickard Öberg

unread,
Sep 22, 2011, 11:17:55 AM9/22/11
to ddd...@googlegroups.com
On 9/22/11 17:02 , Philip Jander wrote:
>> Example: To create an order POST to Orders resource representation of
>> an order. Respond with 201 cretaed with location header which contains
>> order URI with order ID.
>> To delete an order client sends DELETE to order URI
>> To update an order clients PUTS new order representation to order URI.
>
> This is sort of contrary to the CQRS + DDD ideas. As many have already
> stated, you should *not* expose your domain entities as resources. Make
> up are API based on commands and queries which result from your business
> case, not your mental domain model.
> Talk to your business, define user cases and use DDD. Or else, if the
> problem domain is shallow enough, forget about DDD and CQRS altogether.
> For many applications, this is just too heavy a toolset.

Yup. And you might as well skip the "domain" entirely, and go straight
to the database, if it has a "REST" API. I don't know a single database
that actually has a REST API though, although many claim to have.

/Rickard


John Thornborrow

unread,
Sep 22, 2011, 11:31:30 AM9/22/11
to ddd...@googlegroups.com
Then I fear you do not understand REST at all. SELECT/DELETE/UPDATE/INSERT SQL queries are very RESTful. :)

REST is not about what HTTP methods and URLs you use... it's about how you use the tools available to you. 

REST is an architecture style that is completely independent of anything to do with the web and HTTP.

It so happens that HTTP fits very, very well with the purposes of REST.

Remember what REST is an acronym of: Representational State Transfer.

Sharas

unread,
Sep 22, 2011, 12:01:44 PM9/22/11
to ddd...@googlegroups.com
All right, what's your suggestion? We have a concrete use case now, service is described here: http://archfirst.org/books/trading-service

Sharas

unread,
Sep 22, 2011, 12:03:46 PM9/22/11
to ddd...@googlegroups.com
Talking to PhilJ, forgot to address it properly

Rickard Öberg

unread,
Sep 22, 2011, 12:11:49 PM9/22/11
to ddd...@googlegroups.com
On 9/22/11 18:01 , Sharas wrote:
> All right, what's your suggestion? We have a concrete use case now,
> service is described here: http://archfirst.org/books/trading-service

Ok, what is the usecase?

/Rickard

Sharas

unread,
Sep 22, 2011, 12:19:36 PM9/22/11
to ddd...@googlegroups.com
Read service description

Rickard Öberg

unread,
Sep 22, 2011, 12:21:56 PM9/22/11
to ddd...@googlegroups.com
On 9/22/11 18:19 , Sharas wrote:
> Read service description

That is not a usecase. Read up on usecases, and try again.

/Rickard

Sharas

unread,
Sep 22, 2011, 12:35:22 PM9/22/11
to ddd...@googlegroups.com
Richard can be useful only if addressed in a specific format:) Anybody else have a suggestion how to expose capabilities in a described service in a REST'full manner?

Philip Jander

unread,
Sep 22, 2011, 12:39:27 PM9/22/11
to ddd...@googlegroups.com
Am 22.09.2011 18:01, schrieb Sharas:
> All right, what's your suggestion? We have a concrete use case now,
> service is described here: http://archfirst.org/books/trading-service
Disclaimer: Although I have (non-RESTful) CQRS systems in production at
this time, I have not used REST together with CQRS in production, but I
did a spike some time back to evaluate the potential for auto-generating
UIs.

The trading service reads nicely as a CQRS interface, so I would
translate it into a REST interface along the lines of the previous
discussion.
However, I want to point out that this is purely an API description and
I take the methods to be your use cases...

command resources: (PUT, possibly POST, maybe GET)
.../Trading/OpenNewAccount/<cid>
.../Trading/RegisterExternalAccount/<cid>
.../Trading/TransferCash/<cid>
.../Trading/PlaceOrder/<cid>
.../Trading/Order/<id>/CancelOrder/<cid>
If the API is larger and the various account IDs only refer to
non-external accounts, you might want to group commands as resources
below the account concept, e.g. .../Trading/Account/<id>/PlaceOrder/<cid>

queries operate on collections (GET):
.../Trading/Accounts?queryparams
and
.../Trading/Account/Summary/<id>
.../Trading/Account/Information/<id>
etc.

where the response of the former would contain links to the latter.
And the latter would contain links to available commands in which that
account may participate.
You can even have command resources GETable and return empty command
objects to be filled (think autogenerating UI here)...

Personally I still like PUTing commands and be able to get them to
retrieve status info. Especially for a trading system as orders are
idempotent by API design in that case.

So I still stand by my original and very first answer in this thread:
CQRS and REST may play together nicely, but the commands (read use
cases) are the resources, not the entities of the domain behind it.
But I also stand by my last post: if the domain does not contain
complicated rules (and collaboration), DDD + CQRS is maybe not needed at
all here. As from the API interface snippet, it is still hard to judge
the extent of the model behind it and its volatility.

And of course, this is purely IMHO, we have already seen in this thread
that there are a number of different perspectives, mine is way more CQRS
than REST....

Cheers
Phil


Rickard Öberg

unread,
Sep 22, 2011, 12:45:07 PM9/22/11
to ddd...@googlegroups.com

Here's the thing. I can talk about usecases until I'm blue in the face,
and it won't help you a thing if you don't actually know what a usecase
is. So until you know what a usecase is, I can't actually help you, even
if I want to (and I do). See my point?

Let's make it easier: if you were to design a website for users to
access the service, what would it look like? There's no copying of
URL's, creating URL's manually or POST-ing this or that allowed. You can
do is generate HTML, forms, and links, which the user can interpret and
use. That's all. Do that, then remove all styling, add "rel" attributes
on all links and forms, and voila, you have a REST API that is
usecase-oriented.

/Rickard

Naresh Bhatia

unread,
Sep 22, 2011, 12:47:39 PM9/22/11
to ddd...@googlegroups.com
Rickard,

With all due respect, a retail trading system is a well known domain. I like your ideas, but without getting something concrete on the table it is very difficult for me (and perhaps the group) to follow them. As far as I can tell from your posts, there is NO example and NO blog posts out there that implement or interpret REST the right way. So why don't we all work as a team to define use cases the way you like to see them and then define a REST API for them. I will be fully supportive.

Naresh

Rickard Öberg

unread,
Sep 22, 2011, 12:53:38 PM9/22/11
to ddd...@googlegroups.com
On 9/22/11 18:47 , Naresh Bhatia wrote:
> With all due respect, a retail trading system is a well known domain. I
> like your ideas, but without getting something concrete on the table it
> is very difficult for me (and perhaps the group) to follow them. As far
> as I can tell from your posts, there is NO example and NO blog posts out
> there that implement or interpret REST the right way.

That is the sad state of things, yeah.

> So why don't we
> all work as a team to define use cases the way you like to see them and
> then define a REST API for them. I will be fully supportive.

Me too! See my previous response for a start. If you develop a
minimalistic website as if it was intended for a human, where all the
human is supposed to do is go to a given URL and then follow links and
fill in forms, AND ONLY THAT, that is the best way to start thinking
about it. Forget RPC and WebServices, and all that, and think of it
simply as a very very bare website. That is the easiest way to start.
Then replace the human with a system, or something that renders that
website as a rich client (Swing, Flash, AJAX, etc.), and you're good to go.

A REST API is defined, contractually, not by how the URL's are
constructed, but rather by the mediatype and (if you use XHTML or any
link-friendly mediatype) the welldefined "rel" names on links. Clients
should NEVER bother with how URL's are constructed, if you are doing
REST, since they are not allowed to use any URL they have not received
previously as a link or form.

/Rickard

Naresh Bhatia

unread,
Sep 22, 2011, 12:58:27 PM9/22/11
to ddd...@googlegroups.com
To help this further, we also have the UI defined completely (see http://archfirst.org/books/getting-started or a live demo here: http://www.archfirst.org/apps/bfclient-silverlight/bullsfirst.html). Given this we should be able to list the use cases your style.

Naresh

Rickard Öberg

unread,
Sep 22, 2011, 1:02:49 PM9/22/11
to ddd...@googlegroups.com
On 9/22/11 18:47 , Naresh Bhatia wrote:
> With all due respect, a retail trading system is a well known domain. I
> like your ideas, but without getting something concrete on the table it
> is very difficult for me (and perhaps the group) to follow them. As far
> as I can tell from your posts, there is NO example and NO blog posts out
> there that implement or interpret REST the right way.

Actually, now that I think about it, there are tons of examples out
there. We just normally call them "websites", and not REST APIs, but
most of them comply just fine with the REST constraints. It's when we
try to do this for "machines" that it gets all bungled up, and our
experience with services and method calls get in the way.

/Rickard

Sharas

unread,
Sep 22, 2011, 1:03:45 PM9/22/11
to ddd...@googlegroups.com
@Phil: In effect it is RPC tuneling through HTTP, you encode your commands or method names in URI's. It's like you're exposing a DSL of your domain to consumers and consumers need to understand it, you describe semantics of your app that way.

One of the core principles of REST is uniform interface. Fixed language that everybody knows how to use. So you don't have to describe your DSL to each potential client. With this you get much bigger reach of your app. Your semantics transfer to your resource representations. Representations can be manipulated with that fixed language. So if you want to expose some capability, you expose a resource which everybody knows how to consume.

Because of that fixed language you can use web as a platform with huge scale and availability. All intermediaries like proxies do not need to know or understand your representations, but they need to understand semantics of that fixed language. And semantics of webs' laguage is: 
POST is not safe and not idempotent.
PUT is idempotent.
GET is safe
DELETE is idempotent.

Regards,

Sharas

Rickard Öberg

unread,
Sep 22, 2011, 1:17:43 PM9/22/11
to ddd...@googlegroups.com
On 9/22/11 18:58 , Naresh Bhatia wrote:
> To help this further, we also have the UI defined completely (see
> http://archfirst.org/books/getting-started or a live demo here:
> http://www.archfirst.org/apps/bfclient-silverlight/bullsfirst.html).
> Given this we should be able to list the use cases your style.

Awesome! So, given that you can now identify the usecases, and build the
REST API accordingly.

Here's a start:
GET / ->
XHTML with links that can have "rel" set to one of:
"signup"
"login"

GET link with "signup" rel ->
XHTML with form for signup info. Fill in form and submit (with whatever
method the form has as "method" attribute).

GET link with "login" rel ->
XHTML with form for login. Fill in form and submit. Follow redirects.

GET on URL retrieved from redirect ->
XHTML with links that can have "rel" set to one of:
"accounts","positions", etc.

GET link with "transfer" rel ->
XHTML with form for transfer. Fields for from-account and to-account
will have list of available options for accounts. Fill in, select
accounts supplied in form, and submit. Follow redirects.

And so on.. this is the definition of the REST API that you share with
your customers, if you want them to be able to use your service with
their own client. The underlying design of the REST API, i.e. the URL
structure, are details that are not part of the contract. Do whatever
makes sense for you. The REST API contract are the names of the "rel"
attributes, the mediatypes (e.g. XHTML), and HTTP itself.

Is that more clear?

/Rickard

Naresh Bhatia

unread,
Sep 22, 2011, 1:56:53 PM9/22/11
to ddd...@googlegroups.com
Thanks! That's a good start. I will start a new page for the REST API and ask for feedback as I progress.

Naresh

Rickard Öberg

unread,
Sep 23, 2011, 6:30:20 AM9/23/11
to ddd...@googlegroups.com
A clarification:

On 9/22/11 19:17 , Rickard �berg wrote:
> And so on.. this is the definition of the REST API that you share with
> your customers, if you want them to be able to use your service with
> their own client. The underlying design of the REST API, i.e. the URL
> structure, are details that are not part of the contract. Do whatever
> makes sense for you. The REST API contract are the names of the "rel"
> attributes, the mediatypes (e.g. XHTML), and HTTP itself.

What this means is that a REST *API* is defined (when done properly) by
the hypermedia choice and well-defined "rel" link attributes, not by the
URL structure and when to use GET/POST/PUT. The REST API *design and
implementation* consists of the URL structure and choice of methods, but
because that is technically not part of the published API you can change
it at any point in time. Since most REST "API"s consider the URL
structure to be part of the API contract, they have a problem in that it
becomes hard to change. By not making the URL structure part of the
formal contract this gives you a lot of freedom in how to change that as
the system evolves, without breaking any clients (since they are not
allowed to make assumptions about URL's and methods).

One of the key things here is that on the client-side it is advisable to
provide some kind of library that the application developers use, and
which enforce this, i.e. application developers can never say "I want to
call this URL", and instead they are only provided a list of links which
they can choose from, and the library helps with picking the right
method to use to invoke it, rather than the application developer
explicitly doing a POST or a PUT.

So for example, initially you may choose to use POST for some action,
and later redesign it to allow PUT, and the application clients are not
impacted at all, since they never decided explicitly what method to use
anyway. They are just submitting forms, with whatever the form says
should be used as method.

In the human world the "library" we use for this is the browser. It
helps us by providing a rendering of the links and forms, which we
interact with, rather than manually changing the URL in the browser to
access various parts of an application. It needs to be the same for
machine users of a REST API. Then writing apps becomes easy, you need to
worry less about versioning, and the app becomes more scalable as a
result, since a minimal number of HTTP calls are made.

/Rickard

Naresh Bhatia

unread,
Sep 24, 2011, 1:13:15 AM9/24/11
to ddd...@googlegroups.com
Rickard,

Still digesting! In fact quite confused as you will see from my questions below.

Here's what I have so far - I have started creating a "bare" web site as you suggested - using links with "rel" attributes and forms for submitting data. See http://archfirst.googlecode.com/svn/trunk/docs/bullsfirst/rest-prototype/index.html. For example, this page has a link to open an account:

<a rel="openAccount" href="open-account.html">Open an Account</a>

and a form to log in:

<form id="login" action="accounts.html">
    Username: <input type="text" name="username" /><br/>
    Password: <input type="password" name="password" /><br/>
    <input type="submit" value="Login" />
</form>

So far so good. But where to go from here? My fundamental question is are we doing this to identify what goes in the REST API or is this the REST API itself. If this indeed is the REST API, I feel that we have gone well beyond HTTP and starting to rely on HTML. Also it is starting to look like a presentation layer. So let me break this down to some detailed questions.
  • Is the openAccount link shown above relevant to the REST API? Isn't it just navigation that is relevant to the front-end only. Other pages, such as accounts.html, have even more navigational links (e.g. one for each tab). In a  smart front-end, clicking on these links is completely internal to the app and does not require calling any REST APIs.
  • Is the login form shown above relevant to the REST API? A smart front-end does not have to literally grab such a form from the server, it just knows that this information is needed by the server API to login. The point I am trying to make is that a human user can probably adjust to changes in a form on an HTML page, but a program using a REST API can't. For example, if the server suddenly added a field called Device Id to this form, a client program would have no idea what to do with it.
  • The only other interpretation of the link and the form above I can think of is that they help us identify the use cases and the data needed to spec out an API, but they are not the API in themselves.
  • If I wanted to use JSON requests and responses where and how would I specify them?
  • For the accounts page, the server needs to send a list of accounts including flags indicating whether each account is editable or not. Using this information, the front-end can easily create a presentation. Specifically, a link for navigating to a detail page (positions) and another to navigate to an edit page. Again, I see these links as purely navigational within the client and not something that needs to come through REST responses. 

I guess I am having trouble separating presentation stuff from data when using this approach. What am I missing?

Thanks.
Naresh


On Fri, Sep 23, 2011 at 6:30 AM, Rickard Öberg <rickar...@gmail.com> wrote:
A clarification:

Daniel Yokomizo

unread,
Sep 24, 2011, 8:23:05 AM9/24/11
to ddd...@googlegroups.com


On Sep 24, 2011 2:13 AM, "Naresh Bhatia" <bha...@comcast.net> wrote:
>
> Rickard,
>
> Still digesting! In fact quite confused as you will see from my questions below.
>
> Here's what I have so far - I have started creating a "bare" web site as you suggested - using links with "rel" attributes and forms for submitting data. See http://archfirst.googlecode.com/svn/trunk/docs/bullsfirst/rest-prototype/index.html. For example, this page has a link to open an account:
>
> <a rel="openAccount" href="open-account.html">Open an Account</a>
>
> and a form to log in:
>
> <form id="login" action="accounts.html">
>     Username: <input type="text" name="username" /><br/>
>     Password: <input type="password" name="password" /><br/>
>     <input type="submit" value="Login" />
> </form>
>
> So far so good. But where to go from here? My fundamental question is are we doing this to identify what goes in the REST API or is this the REST API itself. If this indeed is the REST API, I feel that we have gone well beyond HTTP and starting to rely on HTML. Also it is starting to look like a presentation layer. So let me break this down to some detailed questions.
> Is the openAccount link shown above relevant to the REST API? Isn't it just navigation that is relevant to the front-end only. Other pages, such as accounts.html, have even more navigational links (e.g. one for each tab). In a  smart front-end, clicking on these links is completely internal to the app and does not require calling any REST APIs.

In REST the client (your smart front end) don’t control the urls or  the hypermedia contents so  it may not  know them in advance, only the  mime types descriptions and rels used.

> Is the login form shown above relevant to the REST API? A smart front-end does not have to literally grab such a form from the server, it just knows that this information is needed by the server API to login. The point I am trying to make is that a human user can probably adjust to changes in a form on an HTML page, but a program using a REST API can't. For example, if the server suddenly added a field called Device Id to this form, a client program would have no idea what to do with it.

Talking about login, it's usually better  to use auth headers instead, so the server only asks for them when required.

Now suppose we deploy a REST app and there's a form reachable to a client with two fields. These are described in the mime type for the representation the form is in. If we add a new field  the server needs to deal with this api  evolution.  It can version the representation and support both (perhaps the action url is different and we have different controllrs responding,  one expecting two fields and one expecting three) provide the form with a default value for the new field, refuse to answer the POST without the new field, refuse to  serve the old version of the mime type (if we versioned the mime type), 404 the url used  to GET the form (if we version  using urls). In REST the server controls the API evolution. The client only follows the links and acts on what it understands. Of course a client needs to be programmed to deal with a specific form or rel, but it may safely ignore whatever other  forms or rels it doesn't understand and still work if the server don't  break the old  use cases.

> The only other interpretation of the link and the form above I can think of is that they help us identify the use cases and the data needed to spec out an API, but they are not the API in themselves.
> If I wanted to use JSON requests and responses where and how would I specify them?

Who is "I" in this sentence? This is supposed to be part  of conneg (i.e. content negotiation), the server can add  and enctype to the form  with the expected Content-Type.

> For the accounts page, the server needs to send a list of accounts including flags indicating whether each account is editable or not. Using this information, the front-end can easily create a presentation. Specifically, a link for navigating to a detail page (positions) and another to navigate to an edit page. Again, I see these links as purely navigational within the client and not something that needs to come through REST responses. 

The server knows the account is editable so it provides the valid transitions (i.e. links or forms). The front end just displays them, without having to check  if the accounts are editable.

Try to think REST as a conversation, the server responds with the next valid steps in the conversation.

Sharas

unread,
Sep 24, 2011, 8:42:21 AM9/24/11
to ddd...@googlegroups.com
Getting back to the original question: As for commands, you can capture users intentions by exposing appropriate resources at whatever granularity you need. It will be restful as long as you don't do RPC tunneling through HTTP. And events can be published as an  ATOM feed. 

Sharas

Vitaly Stakhov

unread,
Sep 26, 2011, 5:37:53 PM9/26/11
to DDD/CQRS
I've been following this thread and the idea of exposing application
state makes perfect sense to me. The question I have is how do we tell
a client which query it should execute after posting a command and
where to display the result of the query.

To clarify the question let's consider an example. Let's say we're
creating a UI similar to gmail but very simplistic as it has only two
folders - Inbox and Spam - and also a list of emails in the currently
selected folder. The usecase in question is marking an email as spam.
After posting the MarkEmailAsSpamCommand (or PUTting or whatever,
doesn't matter now), the client has to know that it should refresh
items in Inbox because the item has gone to the Spam folder. Without
rest api the client just knows which query it should execute and where
on the screen to put the results. That is the client executes 'get-
inbox-items-query' and displays the resultant emails list. Now if we
change the use case slightly so that the Spam folder gets selected to
show the email has been actually moved there, the client knows it
should just switch to the Spam folder and thus executes 'get-spam-
items-query'.

With rest api, the client should be hypermedia driven and what should
be displayed after the command execution should come in response to
posting the command. For example the response could contain the
expected result in payload after the command is executed and the read
side is updated, or just the link to the query the client should GET
on. But how exactly do we know which context the returned query
belongs to - email list or new folder selection?

Rickard Öberg

unread,
Sep 26, 2011, 7:51:55 PM9/26/11
to ddd...@googlegroups.com
On 9/24/11 13:13 , Naresh Bhatia wrote:
> Here's what I have so far - I have started creating a "bare" web site as
> you suggested - using links with "rel" attributes and forms for
> submitting data. See
> http://archfirst.googlecode.com/svn/trunk/docs/bullsfirst/rest-prototype/index.html.
> For example, this page has a link to open an account:
>
> <a rel="openAccount" href="open-account.html">Open an Account</a>
>
> and a form to log in:
>
> <form id="login" action="accounts.html">
> Username: <input type="text" name="username" /><br/>
> Password: <input type="password" name="password" /><br/>
> <input type="submit" value="Login" />
> </form>
>
> So far so good. But where to go from here? My fundamental question is
> are we doing this to identify what goes in the REST API or is this the
> REST API itself. If this indeed is the REST API, I feel that we have
> gone well beyond HTTP and starting to rely on HTML.

Yes, and that is a good thing, although even better would be to use
XHTML, since it is easier to parse as it is proper XML. When doing REST
a key decision is which hypermedia to use. You can XHTML, or a custom
JSON dialect with added links, or Atom. As long as you have support for
links, it is a good start.

> Also it is starting
> to look like a presentation layer.

It is the application layer. In the presentation layer you could
aggregate the usecases exposed by the application layer, so in a proper
presentation layer you might combine several usecases in one screen. The
above would just represent one of those usecases.

> So let me break this down to some
> detailed questions.
>

> * Is the openAccount link shown above relevant to the REST API? Isn't


> it just navigation that is relevant to the front-end only. Other
> pages, such as accounts.html, have even more navigational links
> (e.g. one for each tab). In a smart front-end, clicking on these
> links is completely internal to the app and does not require calling
> any REST APIs.

Clients are not allowed to construct any URL's, so without links, the
client cannot do anything beyond going to the initial URL. It is
"navigation" only in the sense that it shows the structure of the
usecases. In presentation layer navigation you have navigation for
presentation purposes, which might be different. In a simplistic client
there might be a 1-1 mapping, but that is only the simplest case.

> * Is the login form shown above relevant to the REST API? A smart


> front-end does not have to literally grab such a form from the
> server, it just knows that this information is needed by the server
> API to login. The point I am trying to make is that a human user can
> probably adjust to changes in a form on an HTML page, but a program
> using a REST API can't. For example, if the server suddenly added a
> field called Device Id to this form, a client program would have no
> idea what to do with it.

The difference is that if you, for example, add fields to forms, then if
those fields provide defaults, then even old clients that are not yet
updated will still work. If you don't GET the form first, with the
defaults, old clients will break. So doing it this way will help with
versioning.

> * The only other interpretation of the link and the form above I can


> think of is that they help us identify the use cases and the data
> needed to spec out an API, but they are not the API in themselves.

The "rel" names are indeed part of the API, as they form the formal
contract you have with clients. URL's are not a part of the API, at all.
In a proper REST API you should be able to change URL's at any point in
time, with no clients breaking.

> * If I wanted to use JSON requests and responses where and how would I
> specify them?

You would have to specify a dialect of JSON which details how links are
represented. Once you have that you're good to go. This is, in fact,
what I'm doing myself, rather than using XHTML.

> * For the accounts page, the server needs to send a list of accounts


> including flags indicating whether each account is editable or not.
> Using this information, the front-end can easily create a
> presentation. Specifically, a link for navigating to a detail page
> (positions) and another to navigate to an edit page. Again, I see
> these links as purely navigational within the client and not
> something that needs to come through REST responses.

Again, without the server telling the client where the accounts are, the
client would have NO IDEA where those URL's are. My favourite solution
for table-ish data is the Google Data Table API, where you can
effectively have a negotiation between what columns the server offers,
and what the client wants.

I use this, for example, to support both Swing clients and mobile
devices. The Swing client does "select *" whereas the mobile client
would typically do something like "select description, href" to get just
the info needed for a list of links, which when used would provide the
details ("select *").

> I guess I am having trouble separating presentation stuff from data when
> using this approach. What am I missing?

The problem with the SOAPy approach is that you put the application
layer and usecases in the client, so the client is "too smart". Once you
expose usecases from the application layer in the REST API, all that
logic is encoded on the server instead of the client, and the client
then becomes really thin. It then becomes VERY EASY to do multiple
clients, for multiple platforms or devices, which behave exactly the
same way. This is very hard to do if you expose too low-level things,
like the domain model.

I'm wondering: have you read the REST thesis? If not, I think now would
be a good time to do so... it explains a lot of these things, and why
you want to do this in the first place.

regards, Rickard

Raoul Duke

unread,
Sep 26, 2011, 7:54:02 PM9/26/11
to ddd...@googlegroups.com
On Mon, Sep 26, 2011 at 4:51 PM, Rickard Öberg <rickar...@gmail.com> wrote:
> I'm wondering: have you read the REST thesis? If not, I think now would be a
> good time to do so... it explains a lot of these things, and why you want to
> do this in the first place.

i, for one, seem to recall reading it... or trying to read it. it is
great, but it is bad. i think your posts, Rickard, on hateoas helped
me understand it better! :-)

Rickard Öberg

unread,
Sep 26, 2011, 7:57:54 PM9/26/11
to ddd...@googlegroups.com
On 9/24/11 20:23 , Daniel Yokomizo wrote:
> > Is the login form shown above relevant to the REST API? A smart
> front-end does not have to literally grab such a form from the server,
> it just knows that this information is needed by the server API to
> login. The point I am trying to make is that a human user can probably
> adjust to changes in a form on an HTML page, but a program using a REST
> API can't. For example, if the server suddenly added a field called
> Device Id to this form, a client program would have no idea what to do
> with it.
>
> Talking about login, it's usually better to use auth headers instead,
> so the server only asks for them when required.

It depends. Sometimes you may want to use auth headers instead, and that
would be perfectly ok (I do it), but sometimes you may want to have an
explicit login if you need to generate some token instead, and also if
only that page should be using HTTPS. Both are ok, I think. It also
depends on whether the login requires more than just user/password. A
device id is one example, or maybe a strong authentication password from
some hardware thingy. Then headers might not be enough.

> Now suppose we deploy a REST app and there's a form reachable to a
> client with two fields. These are described in the mime type for the
> representation the form is in. If we add a new field the server needs
> to deal with this api evolution. It can version the representation and
> support both (perhaps the action url is different and we have different
> controllrs responding, one expecting two fields and one expecting
> three) provide the form with a default value for the new field, refuse
> to answer the POST without the new field, refuse to serve the old
> version of the mime type (if we versioned the mime type), 404 the url
> used to GET the form (if we version using urls). In REST the server
> controls the API evolution. The client only follows the links and acts
> on what it understands. Of course a client needs to be programmed to
> deal with a specific form or rel, but it may safely ignore whatever
> other forms or rels it doesn't understand and still work if the server
> don't break the old use cases.

Exactly. One problem with current REST API approaches also, from a
client programming perspective, is that they are too imperative, as in
"first do this, then do this, then that". Considering above I think REST
clients need to be able to support more thinking along the lines of "if
this, then that. If this, then that" etc. i.e. more declarative. Then it
becomes easier for the client to react to such changes. So, the problem
is not only that REST API's are screwed up, but also the client side.

/Rickard

Rickard Öberg

unread,
Sep 26, 2011, 7:58:55 PM9/26/11
to ddd...@googlegroups.com

It will be RESTful if you follow the REST constraints. If you don't know
what the REST constraints are, and why they are there, it is VERY
DIFFICULT indeed to do REST.

/Rickard

Rickard Öberg

unread,
Sep 26, 2011, 8:06:08 PM9/26/11
to ddd...@googlegroups.com

Here's how I structure my URL's: anything ending with "/" represents a
usecase. In there you will have queries and commands, e.g. "/index"
query and "/markspam" command. If I have this for the inbox:
"/index"
which returns a Google Data Table that lists the emails, and then the
client selects one email:
/1234/index
-> info about email + link to /1234/markspam
When the client POSTS to "markspam" the result could either be a list of
generated events which the client can react to (this is what I do), or
you could return a redirect to /1234/index to indicate that a refresh
would be "good to do at this point". This is without CQRS/EventSourcing.

However, a client may be showing both the Inbox full list, as well as
the individual email, so how to know that both needs refresh? This is
why I return the list of generated events as command invocation result,
and which is why I think EventSourcing really works well with REST APIs.
Clients who understand these can then on their own figure out what to
refresh. In my client I simply notify all active views of what events
have just been created, so any view might react to the events.

/Rickard

Vitaly Stakhov

unread,
Sep 27, 2011, 3:55:40 AM9/27/11
to DDD/CQRS
Having events as part of the response and allowing the views to choose
which one to react to sounds like a good solution for me.

However notifying all views of the returned events is raising the
level of awareness of the client. Now the client is not entirely
stupid as it should understand what exactly it should do in order to
react to specific events e.g. execute '/index' query and thus refresh
emails list when 'marked spam' event is returned.

Exposing events as resources won't work either as handling the same
event is different per each view.

Making clients smarter in this respect may be an ok thing to do.
Drawing parallels with websites we can rarely see them entirely stupid
on the client side these days.

Thoughts?

Graeme Foster

unread,
Sep 27, 2011, 4:03:05 AM9/27/11
to ddd...@googlegroups.com
I'll admit I've lost track of this very interesting thread a bit, but doesn't returning stuff from a request mean you're not doing CQRS any more? In order to send the resulting events back to the client that means the client will have to wait for the command to get processed by the domain model, which could take a while. And telling the client what it should refresh also assumes that the read models will have been updated by the time it reads from them.

I'm sure I must have missed an important point that someone made earlier, but it would help me if someone could fill me in :)

G.
--
Graeme Foster

Philip Jander

unread,
Sep 27, 2011, 4:01:22 AM9/27/11
to ddd...@googlegroups.com
Hi Rickard,

>
> However, a client may be showing both the Inbox full list, as well as
> the individual email, so how to know that both needs refresh? This is
> why I return the list of generated events as command invocation
> result, and which is why I think EventSourcing really works well with
> REST APIs. Clients who understand these can then on their own figure
> out what to refresh. In my client I simply notify all active views of
> what events have just been created, so any view might react to the
> events.
>
>

I have been wondering about whether and to what extent publish domain
events. Do you just send event type and aggregate ID or actual events
including properties? My events can at times contain sensitive
information that I do not really want to be broadcasted.
So for the moment I just provide the aggregate IDs which were touched
plus responsible user ID. My clients act on detecting a known aggregate
ID with refreshing their models, or warning the user of possible
concurrency if the event originated from another session.
I thought about either providing more verbose client-side events
aggregated out of domain events, or annotate event properties with
privacy information and strip down to the acceptable subset when
serialising, but haven't really tried either in full. Do you have any
suggestions?

Cheers
Phil

Rickard Öberg

unread,
Sep 27, 2011, 4:08:17 AM9/27/11
to ddd...@googlegroups.com
On 9/27/11 15:55 , Vitaly Stakhov wrote:
> Having events as part of the response and allowing the views to choose
> which one to react to sounds like a good solution for me.
>
> However notifying all views of the returned events is raising the
> level of awareness of the client. Now the client is not entirely
> stupid as it should understand what exactly it should do in order to
> react to specific events e.g. execute '/index' query and thus refresh
> emails list when 'marked spam' event is returned.

First of all /index is not an event, but as you say, it's a query.

What would happen is that the views get notified with the events that
are returned, from any command invocation, and whenever they see
something they're interested in (whether it was "that" view which caused
it is unimportant), they can update appropriately.

> Exposing events as resources won't work either as handling the same
> event is different per each view.

Yup.

/Rickard

Rickard Öberg

unread,
Sep 27, 2011, 4:11:20 AM9/27/11
to ddd...@googlegroups.com
On 9/27/11 16:01 , Philip Jander wrote:
> I have been wondering about whether and to what extent publish domain
> events. Do you just send event type and aggregate ID or actual events
> including properties?

I send the whole thing, but the client views actually never use that.
They only look at what usecase triggered it, the name of the event, and
the id of the affected entity. I have so far never used the actual event
payload. So that would probably be optional, especially if it's
sensitive information and you don't do HTTPS encryption of the connection.

> My events can at times contain sensitive
> information that I do not really want to be broadcasted.
> So for the moment I just provide the aggregate IDs which were touched
> plus responsible user ID. My clients act on detecting a known aggregate
> ID with refreshing their models, or warning the user of possible
> concurrency if the event originated from another session.
> I thought about either providing more verbose client-side events
> aggregated out of domain events, or annotate event properties with
> privacy information and strip down to the acceptable subset when
> serialising, but haven't really tried either in full. Do you have any
> suggestions?

Right, one way is to "aggregate" the events on the serverside into
client refresh events. I've seen systems do that. To me that pushes too
much understanding of the client to the server, but if you only have one
client, then sure.

/Rickard

Rickard Öberg

unread,
Sep 27, 2011, 4:14:07 AM9/27/11
to ddd...@googlegroups.com
On 9/27/11 16:03 , Graeme Foster wrote:
> I'll admit I've lost track of this very interesting thread a bit, but
> doesn't returning stuff from a request mean you're not doing CQRS any
> more? In order to send the resulting events back to the client that
> means the client will have to wait for the command to get processed by
> the domain model, which could take a while. And telling the client what
> it should refresh also assumes that the read models will have been
> updated by the time it reads from them.
>
> I'm sure I must have missed an important point that someone made
> earlier, but it would help me if someone could fill me in :)

Right, so this is for synchronous command processing. My commands ALWAYS
only touch the domain model, so they are relatively quick to process.
Anything more complicated than that, let's say sending an email, is done
by listeners on the events, so that retries and such can be done.

For example, I have a domain model for basically a discussion thread.
The command would post a new message on the discussion object model,
which would generate events that a service then reads and generates the
associated emails. So the posting itself is fast, while the service
reaction to it might be slow. Which is fine.

/Rickard

Graeme Foster

unread,
Sep 27, 2011, 4:20:10 AM9/27/11
to ddd...@googlegroups.com
On 27 September 2011 09:14, Rickard Öberg <rickar...@gmail.com> wrote:
Right, so this is for synchronous command processing. My commands ALWAYS only touch the domain model, so they are relatively quick to process. Anything more complicated than that, let's say sending an email, is done by listeners on the events, so that retries and such can be done.

For example, I have a domain model for basically a discussion thread. The command would post a new message on the discussion object model, which would generate events that a service then reads and generates the associated emails. So the posting itself is fast, while the service reaction to it might be slow. Which is fine.

OK, so there's no queueing of commands before they get to the domain in this case. Gotcha.

Maybe this is why the thread was back and forth over exposing the domain model vs. commands as RESTful resources earlier on - it depends!

Thanks,
G.
--
Graeme Foster 

Sarunas Mazylis

unread,
Sep 27, 2011, 4:26:06 AM9/27/11
to ddd...@googlegroups.com
There can be queuing. after POST you can respond with 202 accepted and provide location header where client can pull for result.
You can also use ATOM PUB to post to queues and pull on them.

Sharas

Rickard Öberg

unread,
Sep 27, 2011, 4:26:18 AM9/27/11
to ddd...@googlegroups.com
On 9/27/11 16:20 , Graeme Foster wrote:
> OK, so there's no queueing of commands before they get to the domain in
> this case. Gotcha.
>
> Maybe this is why the thread was back and forth over exposing the domain
> model vs. commands as RESTful resources earlier on - it depends!

Always! This industry is extreme in that sense, because pretty much
anything comes down to "it depends".

For example, if you don't need the constraints that REST adds, then..
don't do it. Do something else with HTTP that is not REST (like, pretty
much everyone)! But if you like the constraints, because you like the
tradeoffs that this implies (pros AND cons), then go for it!

As an example, to me it makes no sense whatsoever for a database to have
a REST API. HTTP API, absolutely, but REST? Why? The constraints that
are imposed in REST doesn't seem to fit with the requirements of a
database. And, if you look closely (almost) none of the databases that
say they have a REST API actually do. There are lovely HTTP API's
though, which don't follow the REST constraints. So naming the damn
thing they're doing correctly is the biggest problem, as far as I'm
concerned.

/Rickard

Rickard Öberg

unread,
Sep 27, 2011, 4:27:37 AM9/27/11
to ddd...@googlegroups.com
On 9/27/11 16:26 , Sarunas Mazylis wrote:
> There can be queuing. after POST you can respond with 202 accepted and
> provide location header where client can pull for result.
> You can also use ATOM PUB to post to queues and pull on them.

Or combine with a WebSocket that streams them back asynchronously. So
many options... it all depends...

/Rickard

Graeme Foster

unread,
Sep 27, 2011, 4:53:58 AM9/27/11
to ddd...@googlegroups.com
On 27 September 2011 09:26, Sarunas Mazylis <apkr...@gmail.com> wrote:
There can be queuing. after POST you can respond with 202 accepted and provide location header where client can pull for result.
You can also use ATOM PUB to post to queues and pull on them.

In that case wouldn't the "commands as resources" solution be a better fit? You're POSTing a command and polling it for progress/completion/results. Doesn't seem to fit with exposing the domain model as resources to me.

G.
--
Graeme Foster

Sarunas Mazylis

unread,
Sep 27, 2011, 5:04:24 AM9/27/11
to ddd...@googlegroups.com
I didn't say you should expose your domain as resources. It should be pretty anemic domain if you can directly expose it as resources.

Sharas

Rickard Öberg

unread,
Sep 27, 2011, 5:25:47 AM9/27/11
to ddd...@googlegroups.com
On 9/27/11 16:53 , Graeme Foster wrote:
> On 27 September 2011 09:26, Sarunas Mazylis <apkr...@gmail.com
> <mailto:apkr...@gmail.com>> wrote:
>
> There can be queuing. after POST you can respond with 202 accepted
> and provide location header where client can pull for result.
> You can also use ATOM PUB to post to queues and pull on them.
>
>
> In that case wouldn't the "commands as resources" solution be a better
> fit? You're POSTing a command and polling it for
> progress/completion/results. Doesn't seem to fit with exposing the
> domain model as resources to me.

You could do "commands as resources" and still return 202 as the result.
Should be ok.

/Rickard

Nuno Lopes

unread,
Sep 27, 2011, 6:03:37 AM9/27/11
to ddd...@googlegroups.com
I read the thesis and its content seams to be highly contradictory.

In the end I felt, ... syntactic and protocol sugar apart what is this trying to solve really? 

The difference is that if you, for example, add fields to forms, then if those fields provide defaults, then even old clients that are not yet updated will still work.

Garbage. Try that on Mobile Web Apps. REST is not enough. Look at Google. They are probably the ones using REST (or something ver close the most) and look at the supported browser versions. If some field becomes mandatory the UI is useless unless you have multiple API versions in which case REST is not the only solution.

Again, without the server telling the client where the accounts are, the client would have NO IDEA where those URL's are. 

Why? 

The problem with the SOAPy approach is that you put the application layer and usecases in the client, so the client is "too smart". Once you expose usecases from the application layer in the REST API, all that logic is encoded on the server instead of the client

Most our Web Apps only do field validation on the client side. My problem is not really about constructing URL, I guess.

The hardest part about exposing usecases is that you have to actually know what they are. But that's a GOOD problem, and finding that out is in line with DDD in general, and understanding the business problems as well.

Once you know what they are, we don't need REST.

To me there is a big difference here. First of all, I can create a link to the first, but no to the second, thus informing the client about the possible next states.

Isn't that what the Controller in MVC does? I mean, the Controller maps the use case to the Domain API. If the View representation can be anything. In order words it serves execution paths base on the domain state. Calculating all possible next states is hardly a deterministic endeavor. 

Also, I can do a GET on the first and either get 200 (=it's ok to perform the command) or 404 (=it's not ok to perform the command),

Why is that an advantage of REST only?

which is very important from a UI point of view. Never allow UI's to "try" commands that are sure to fail. The first variant helps, whereas the second don't.

How does it help?

Cheers,

Nubno

Daniel Yokomizo

unread,
Sep 27, 2011, 6:35:29 AM9/27/11
to ddd...@googlegroups.com

This doesn't need to be sync at all. The client can send one way commands and subscribe to the event stream. Also CQRS can be sync or async.

Daniel Yokomizo

unread,
Sep 27, 2011, 9:27:57 AM9/27/11
to ddd...@googlegroups.com

Nuno, check this presentation and see if it makes the "why" clearer:
http://www.slideshare.net/trilancer/why-hateoas-1547275

Nuno Lopes

unread,
Sep 27, 2011, 10:31:23 AM9/27/11
to ddd...@googlegroups.com
Hi, thank you for the slide. But it does not :(

1) If changing URI's where a problem then UDDI would be a huge success (slide 24). But guess what It did not catch. So I'm assuming the there must be something else in REST for us to be so excited. There are better ways to solve this problem IMHO with transparent routing.

2) On slide 27 you could easily see the problem of REST. The client still needs to know the location. I rather prefer the DNS solution. Locations are given virtual names the remain stable and some DNS resolves the names to IP's (the actual locations). I'm using DNS as a metaphor. There is nothing messy about Freeparkers!If you think about it, in REST freeparkers are still being used by the server to calculate resource. Yet they are calculated prior the need to use them which is less efficient in terms of resource allocation. 

You see, we give a lot of credit to Hytertext and HTML on the net. Indeed it is deserved. But in terms of resource location there is still something better then DNS to be found.

One thing that helps making Interfaces stable is polymorphism. As long as the new interfaces also respects the interface of the current it assures retro-compatibility. No need for default values and versioning. So the URI does not change from Pro to Free. WebServices capture this well and in comparison with the trickery shown on the first slides in order to support retro compatibility is seams to be a better approach (just provide the WSDL, who cares for the actual location of the resource, there can be several physical locations for the same resource).

Just some thoughts,

Cheers,

Nuno
PS: For almost any REST example I was given an example I've found a simpler and realistic solution. This is not to say that there aren't probably cases out there where REST is a perfect fit, well the Web/HTTP/HTML is one of them. REST is an abstraction of such architecture but there are other reason why the Web scales so well but Hypertext if you know what I mean.

Sharas

unread,
Sep 27, 2011, 11:52:06 AM9/27/11
to ddd...@googlegroups.com
Here's the thing. I don't think exposing commands as resources is RESTfull. It reeks of RPC tunneling through HTTP. Resources have a lyfecycle influenced by server and client. 

E.G. client can issue DELETE to order resource, server interprets it as "cancel order" users intention. So it does not map to CancelOrder resource.

As for exposing domain as resources: If you can do it you're probably not really capturing and automating your domain. Resources form a layer for interactions, application protocol. Same as you application layer or service layer isn't your domain.


Sharas

Greg Young

unread,
Sep 27, 2011, 2:14:01 PM9/27/11
to ddd...@googlegroups.com

I would tend to agree with the assessment here in the delete case. Create as well.. it is more interresting with updates

Rickard Öberg

unread,
Sep 27, 2011, 10:02:11 PM9/27/11
to ddd...@googlegroups.com
On 9/27/11 23:52 , Sharas wrote:
> Here's the thing. I don't think exposing commands as resources is
> RESTfull. It reeks of RPC tunneling through HTTP. Resources have a
> lyfecycle influenced by server and client.

What REST constraint does it violate?

> E.G. client can issue DELETE to order resource, server interprets it as
> "cancel order" users intention. So it does not map to CancelOrder resource.

What if you need to provide a comment when you cancel an order?

How do you know that DELETE on order is "cancel" rather than "finished
handling" or "delivered" or "processed"?

> As for exposing domain as resources: If you can do it you're probably
> not really capturing and automating your domain. Resources form a layer
> for interactions, application protocol. Same as you application layer or
> service layer isn't your domain.

That is why you should expose your usecases as REST resources. The
usecases are your commands and queries.

/Rickard

Rickard Öberg

unread,
Sep 27, 2011, 10:23:49 PM9/27/11
to ddd...@googlegroups.com
On 9/27/11 18:03 , Nuno Lopes wrote:
> Garbage. Try that on Mobile Web Apps. REST is not enough. Look at
> Google. They are probably the ones using REST (or something ver close
> the most) and look at the supported browser versions. If some field
> becomes mandatory the UI is useless unless you have multiple API
> versions in which case REST is not the only solution.

That has nothing to do with REST as such I'm afraid. It only shows that
there is more understanding to be done for how to implement it properly,
and so far, with the amount of cluelessness about REST that is around
(your posts are a good example), it would be surprising to see anything
else.

>> Again, without the server telling the client where the accounts are,
>> the client would have NO IDEA where those URL's are.
>
> Why?

Because that would imply that there is an out-of-band contract for how
to create those URLs, which means that if the URLs change, the client
breaks, which is one of the problems that REST fixes by relying on
hypermedia to discover those URLs.

>> The problem with the SOAPy approach is that you put the application
>> layer and usecases in the client, so the client is "too smart". Once
>> you expose usecases from the application layer in the REST API, all
>> that logic is encoded on the server instead of the client
>
> Most our Web Apps only do field validation on the client side. My
> problem is not really about constructing URL, I guess.

But if you have a client that "knows" how to construct URLs, that means
if you change them, the clients break. With REST, where hypermedia is
used to discover URLs, URLs are considered an internal implementation
detail that can change at any time. Remember that changing URLs does not
necessarily mean that the path changes. It could just as well be that
the server changes. Let's say you have a main server for the bulk of the
API, but a particular server for one particular query that is heavy to
perform and is used a lot. With REST, where the URLs are discoverable,
you can easily change the server layout on the fly to handle this. With
clients "knowing" how to construct URLs, you are in trouble, and have to
do other tricks to get around it.

>> The hardest part about exposing usecases is that you have to actually
>> know what they are. But that's a GOOD problem, and finding that out is
>> in line with DDD in general, and understanding the business problems
>> as well.
>
> Once you know what they are, we don't need REST.

REST just makes it easier to implement them, since the outcome of
understanding the problem are usecases (commands and queries), and REST
is really good at dealing with that, if you expose the commands and
queries as first-class resources.

>> To me there is a big difference here. First of all, I can create a
>> link to the first, but no to the second, thus informing the client
>> about the possible next states.
>
> Isn't that what the Controller in MVC does? I mean, the Controller maps
> the use case to the Domain API. If the View representation can be
> anything. In order words it serves execution paths base on the domain
> state. Calculating all possible next states is hardly a deterministic
> endeavor.

MVC is used on the client. If you want the Controller to make these
decisions then 1) the controller needs to get that domain state from the
server, which means you are exposing domain state through REST (or
WebServices, or CORBA, or whatever), which leads to chatty interfaces 2)
you have the risk of multiple clients with different controllers having
different rules for the application state and 3) doing authorization
properly will be VERY HARD since most auth rules I've worked with
require domain state, so you need to expose that to the client which
then says "oh this user does not have permission to do this, oops" (but
then the state is already exposed).

You are just getting yourself into a world of pain. Been there, done
that, moving on.

>> Also, I can do a GET on the first and either get 200 (=it's ok to
>> perform the command) or 404 (=it's not ok to perform the command),
>
> Why is that an advantage of REST only?

Well, SOAP, for example, can't do it. You have to introduce your own
services on top of SOAP to be able to ask the server what you can do.
But then again, you said that such decisions are made on the client by
the Controller, so you don't see the problem. But then you will have the
1-2-3 problems above.

>> which is very important from a UI point of view. Never allow UI's to
>> "try" commands that are sure to fail. The first variant helps, whereas
>> the second don't.
>
> How does it help?

When the server expose usecases (commands and queries), the client can
ask the server at any time "what can I do now" and the response comes in
the form of either 200/404 if you "try the command", but more
realistically, it will come in the form of hypermedia with links that
say "given the current application state, this is what you can do next".
The existence of a link with a given rel is then used to enable/disable
operations in the UI. For example, if an email has already been marked
as spam, then when you get the hypermedia for the email (in the previous
example) you will not get a link with rel "markspam" and so you can hide
or disable the "markspam" button.

/Rickard

Sharas

unread,
Sep 28, 2011, 4:03:05 AM9/28/11
to ddd...@googlegroups.com

> Here's the thing. I don't think exposing commands as resources is
> RESTfull. It reeks of RPC tunneling through HTTP. Resources have a
> lyfecycle influenced by server and client.
What REST constraint does it violate?

Uniform interface

> E.G. client can issue DELETE to order resource, server interprets it as
> "cancel order" users intention. So it does not map to CancelOrder resource.

What if you need to provide a comment when you cancel an order?

You might wanna create CanceledOrders resource and have client pot orders to it with comments and whatever else you need.


How do you know that DELETE on order is "cancel" rather than "finished
handling" or "delivered" or "processed"?

Depends on a context of an app


> As for exposing domain as resources: If you can do it you're probably
> not really capturing and automating your domain. Resources form a layer
> for interactions, application protocol. Same as you application layer or
> service layer isn't your domain.

That is why you should expose your usecases as REST resources. The
usecases are your commands and queries.

bolox

Nuno Lopes

unread,
Sep 28, 2011, 6:08:58 AM9/28/11
to ddd...@googlegroups.com
Hi Rickard,

Thanks for the response. Inline ..

That has nothing to do with REST as such I'm afraid.

The response was in the context of REST facilities to support multiple client versions and application interface evolution. If that has nothing to todo with REST then your conclusion is only natural.

It only shows that there is more understanding to be done for how to implement it properly, and so far, with the amount of cluelessness about REST that is around (your posts are a good example), it would be surprising to see anything else. 

That maybe the case, but I'll pass that judgement and focus on subject.

Because that would imply that there is an out-of-band contract for how to create those URLs, which means that if the URLs change, the client breaks, which is one of the problems that REST fixes by relying on hypermedia to discover those URLs.

REST does not fix that neither it is prescriptive on that matter. You see broken links happen all the time in the WWW space, which is a REST implementation. There are several reason for this to happen but Caching may be one of those. Or simply the resource is no longer available.

Indeed one of the benefits of using Web Architectures (REST) is that it fairly resilient to out of band stuff. In you case what fixes the problem of broken links is your App or System does by querying internally the available resource locations for a given URN (or some other internal naming scheme) for constructing the URL, or if you prefer use the hypermedia to discover URLs.

The question is, is that the only way to fix it?

The URI is an acronym for Universal Resource Identifier. There are two specialization on this. One is URN which corresponds to Universal Resource Name and another to Universal Resource Location. Most discussion I see on REST make use of the URL specialization rather then URN. To build the URL then the server does more or less what I said above.

But if we return URN instead of URL? This means that URN would need to be resolved on request much like Domain Names are resolved to IP's. The Interface would be more stable etc.

By fixing this is way the interfaces become more predictable (one may call it uniform?), hence less opportunity for errors. 

But if you have a client that "knows" how to construct URLs, that means if you change them, the clients break. 

I wouldn't say the client needs how to construct URLs, but it definitely needs to know the service Interface. How that interface is mapped to an HTTP request that is an implementation detail.

REST just makes it easier to implement them, since the outcome of understanding the problem are usecases (commands and queries), and REST is really good at dealing with that, if you expose the commands and queries as first-class resources.

As far as I read, REST is not prescriptive on that either. I mean, using domain use cases as Resources. Having said this, IMHO slicing application features base on use cases is a good practice. Wether designing WebServices,  REST Services, COM Services, CORBA Services, J2EE or whatever.

For instance we could:

- URN:MadeWinners/OrderVerification
- URN:MadeWinners/OrderSubmission

Or

- URN: MadeWinners/OrderProcessing/OrderSubmission/
- URN: MadeWinners/OrderManagement/OrderVerification/

MVC is used on the client. If you want the Controller

MVC is not prescriptive on that either. You can have the Views in the Client and the Controller on the server.

Been there, done that, moving on.

I think we have been there doing things differently then what you described.

The Web clients I've built using WWW tech where basically thin and stupid. The intelligence always relied on the server rendering the client representations. This is about to change with HTML5 features taking advantage of technology evolution. It has been noted that traditional thin clients are great for deployment but not so good for interaction. So we need to devise schemes based on REST or something else to leverage the capacities of more powerful clients to improve interaction. So the question is really how deployment can be solved for those situations. Schemes such as App Stores is a way to deal with it. Let's see what lies ahead.

When the server expose usecases (commands and queries), the client can ask the server at any time "what can I do now" and the response comes in the form of either 200/404 if you "try the command", but more realistically, it will come in the form of hypermedia with links that say "given the current application state, this is what you can do next". 

I've been doing that. Yet the client never asks! Only what the client can do is given to it by the server.

Here is problem to solve. Suppose I have three use cases mapped to REST resources. For simplicity ...

UserAuthentication, OrderProcessing, CatalogueBrowsing.

OrderProcessing can only work if an user is authenticated. CatalogueBrowsing works either way.

UserAuthentication resource validates and checks state about user authentication. If a user is not authenticated he can only Login and if it is he can only Logout. So upon Login an Lougout Url is returned, and upon Logout a Login Url is returned.

OrderProcessing does more things. But for brevity let's say that once a user is logged in it can Submit an order.

CatalogueBrowser also does a lot of things, but let's say that it the user can browse either way.

The user is on a screen ready to submit the Order. In this screen does not present the Catalogue browser representations, only User Authentication and OrderProcessing. 

Instead of Submitting the Order the user decided to Logout. What or who should decide which representation should be shown or not next. According to your solution it seams that the client would query all the resources it know to check what needs to be presented. This is hardly not chatty. This or the all the resources should know about each others.

Point being here is that you need a coordinator across resources either in Client or the Server.

Putting this subject to REST what REST says is that SOAP is unnecessary since the existing REST capabilities on HTTPS are enough. Technically I agree and I'm all for it. 

Yet some go further as to say that interface definitions are no longer necessary to be known by the client a priori since the it provided according to current app state. Technically I agree, we can make demos and some simple apps showing this, but the resulting effect is not the best IMHO in the most cases. In the end people bend the rules. If bending the rules is the norm that the premiss is not delivered, period. It is just not because people don't know enough, maybe it is just more complex then people think it should.

Cheers,

Nuno





Sharas

unread,
Sep 28, 2011, 8:52:29 AM9/28/11
to ddd...@googlegroups.com
Yes, I guess HTTPs' application protocol will not be sufficient to get some equivalent of inductive UI or in general intention capturing interface. So HTTPs' app protocol will get extended with custom media type. E.G. link relations will add semantics to resources, but those resources should still be consumed with HTTPs' app protocol. So update will be meaningful in context of those added semantics from custom media format.

I think treating resources as commands does not extend HTTPs' app protocol, it kinda overrides it. And with that, at least partially, you say goodbye to ubiquitous tooling and what they call web as a platform.

Off course it will work if that's good enough for your needs, but the thread is about REST, hence all the commotion.

What do you think?


Sharas

Sharas

unread,
Sep 28, 2011, 8:53:26 AM9/28/11
to ddd...@googlegroups.com
talking to Greg, forgot to address it properly again.

Rickard Öberg

unread,
Sep 29, 2011, 12:51:50 AM9/29/11
to ddd...@googlegroups.com
On 9/28/11 16:03 , Sharas wrote:
>
> > Here's the thing. I don't think exposing commands as resources is
> > RESTfull. It reeks of RPC tunneling through HTTP. Resources have a
> > lyfecycle influenced by server and client.
> What REST constraint does it violate?
>
> Uniform interface

How does it violate the uniform interface? I don't see that...

> > E.G. client can issue DELETE to order resource, server interprets it as
> > "cancel order" users intention. So it does not map to CancelOrder
> resource.
>
> What if you need to provide a comment when you cancel an order?
>
> You might wanna create CanceledOrders resource and have client pot
> orders to it with comments and whatever else you need.

So you will have one resource for listing cancelled orders and doing the
actual cancelling? And how does the client get the link to do that?

> How do you know that DELETE on order is "cancel" rather than "finished
> handling" or "delivered" or "processed"?
>
> Depends on a context of an app

And how do you communicate that context?

> > As for exposing domain as resources: If you can do it you're probably
> > not really capturing and automating your domain. Resources form a layer
> > for interactions, application protocol. Same as you application layer or
> > service layer isn't your domain.
>
> That is why you should expose your usecases as REST resources. The
> usecases are your commands and queries.
>
> bolox

Why?

/Rickard

Sharas

unread,
Sep 29, 2011, 6:01:19 AM9/29/11
to ddd...@googlegroups.com
>  > Here's the thing. I don't think exposing commands as resources is
>  > RESTfull. It reeks of RPC tunneling through HTTP. Resources have a
>  > lyfecycle influenced by server and client.
> What REST constraint does it violate?
>
> Uniform interface

How does it violate the uniform interface? I don't see that...

Since CancelOrder is an endpoint, not a resource, you cannot manipulate it with uniform interface, e.g can you query CancelOrder? Is that even meaningful? That's right, it's not, because CancelOrder is an endpoint not a resource. You will be better off with SOAP and RPC tunneling with that mindset.

>  > E.G. client can issue DELETE to order resource, server interprets it as
>  > "cancel order" users intention. So it does not map to CancelOrder
> resource.
>
> What if you need to provide a comment when you cancel an order?
>
> You might wanna create CanceledOrders resource and have client pot
> orders to it with comments and whatever else you need.

So you will have one resource for listing cancelled orders and doing the
actual cancelling? And how does the client get the link to do that?

I would provide a link to it as a response to some client manipulation of resource. e.g creating an order by posting to Orders resource. It can also be provided as a description of collection in ATOM Pub service document.

> How do you know that DELETE on order is "cancel" rather than "finished
> handling" or "delivered" or "processed"?
>
> Depends on a context of an app

And how do you communicate that context?

The idea is that you don't have to communicate exact meaning of DELETE. Server can interpret it as "archive order", "cancel order", "self destruct in 5 seconds". As long as server responds with 2xx status client can know that it is free of some obligation, it communicated the wish to terminate something, and server agreed. Client can also issue OPTIONS request to see if he can even terminate that obligation. Client can also communicate an end of some process this way.

>  > As for exposing domain as resources: If you can do it you're probably
>  > not really capturing and automating your domain. Resources form a layer
>  > for interactions, application protocol. Same as you application layer or
>  > service layer isn't your domain.
>
> That is why you should expose your usecases as REST resources. The
> usecases are your commands and queries.
>
> bolox

Why?

My statement did not lead to your conclusion. If you want to see yourself as right no matter what then anything can be a sign that you're right in your head. 

Sharas

Philip Jander

unread,
Sep 29, 2011, 9:36:14 AM9/29/11
to ddd...@googlegroups.com

Hi Sharas,

Since CancelOrder is an endpoint, not a resource, you cannot manipulate it with uniform interface, e.g can you query CancelOrder? Is that even meaningful? That's right, it's not, because CancelOrder is an endpoint not a resource. You will be better off with SOAP and RPC tunneling with that mindset.

I guess this whole thread comes down to a matter of perspective: IMHO there are (minimum) two ways to look at the CQRS-REST relationship.

First: can REST-based systems be modeled in a CQRS way and/or do they benefit from it?
Second: can CQRS-based systems be provided through a REST interface?

If you start out from the first perspective, there really is not that much common ground, if one assumes systems designed around allowing the clients to access a model made up of resources which are commonly modified through the four http verbs.
Current CQRS thinking sort of prohibits exposing your domain model state to the client for modification (no setters). Actually you shouldn't even be able to access the write model's state at all (no getters). Hence there is quite a conceptual mismatch.

The second question is quite different however. If you have a CQRS system, its interface by definition consists of commands and queries. Is it possible to expose those as resources and design a REST-based API which is based on letting the client discover those resources, state and legal transitions through hypertext documents (be they XHTML, XML, JSON+links or whatever)? Sure, because you can still achieve the benefits of reducing the necessary API knowledge in your clients. But you have to accept CQRS before trying to provide a REST interface for a CQRS system! And that means that the interface is only commands and queries. The domain model is completely hidden to the clients. There need not be a domain model at all. CQRS is fine with transaction script-based command handlers, too - for small contexts.

Can you GET a CancelOrder command resource? Of course. If it doesn't exist, you get a blank command object, if it exists, you get your original command plus its execution meta data (e.g. published events resulting from that command). YMMV here.

Compared to a domain-object-as-resource approach, this may very well look a bit like RPC (just remember the client doesn't know the commands beforehand, they need to be discovered!).
All the same, exposing non command resources for POST GET PUT and DELETE looks a lot like anemic domain model from the CQRS side of things.

Maybe, it's really just a matter of perspective and maybe there are more of them then the two sketched above...

Phil
It is loading more messages.
0 new messages