Assuming you already have discovered the post URI and thus the URI of the association resource (considered to be $association_uri
in the following), it generally takes these steps:
-
Discover the collection resource managing comments:
curl -X GET http://localhost:8080 200 OK { _links : { comments : { href : "…" }, posts : { href : "…" } } }
-
Follow the
comments
link andPOST
your data to the resource:curl -X POST -H "Content-Type: application/json" $url { … // your payload // … } 201 Created Location: $comment_url
-
Assign the comment to the post by issuing a
PUT
to the association URI.curl -X PUT -H "Content-Type: text/uri-list" $association_url $comment_url 204 No Content
Note, that in the last step, according to the specification of text/uri-list
, you can submit multiple URIs identifying comments separated by a line break to assign multiple comments at once.
A few more notes on the general design decisions. A post/comments example is usually a great example for an aggregate, which means I’d avoid the back-reference from the Comment
to the Post
and also avoid the CommentRepository
completely. If the comments don’t have a lifecycle on their own (which they usually don’t in an composition-style relationship) you rather get the comments rendered inline directly and the entire process of adding and removing comments can rather be dealt with by using JSON Patch. Spring Data REST has added support for that in the latest release candidate for the upcoming version 2.2.