0

Suppose that we have a Post resource (this is just a dummy example):

GET /api/posts/1

{
  "id": 1,
  "header": null,
  "content": null
}

And now we'd like to create a Header inside the Post#1.

POST /api/posts/1/header

{
  "color": "blue",
  "title": "Some title"
}

Now, is it okay for the POST request above to return the following response?

{
  "id": 1,
  "header": {
    "id": 1,
    "color": "blue",
    "title": "Some title"
  },
  "content": null
}

So, basically, a Header was created inside the Post and returned as part of the Post.

Also, if we need to GET the header for Post#1:

GET api/posts/1/header

 {
   "id": 1,
   "color": "blue",
   "title": "Some title"
}

So here only the Header is returned.

3
  • How do you define "okay?" Apr 3, 2021 at 15:25
  • @RobertHarvey I mean, would it be considered a good way to do so? Doesn't it go against REST API design principles that I maybe am missing out? Apr 3, 2021 at 16:10
  • 1
    REST API design principles exist to fulfill specific needs. Do you have those needs? Note: You can read Roy Fielding's dissertation on REST to determine what problems REST solves, or you can read this. Apr 3, 2021 at 19:20

1 Answer 1

3

is it okay for the POST request above to return the following response?

Yes, that is OK.

That said, you've now got two different copies of the header; one in the representation of /api/posts/1 and one in the representation of the header resource itself in /api/posts/1/header, so you have left yourself open to the risk that different representations of the header get cached, and that the client will see conflicting representations of the two resources.

So it might be better to link to the new resource, rather than embedding its representation directly

{
  "id": 1,
  "header": "/api/posts/1/header"
  "content": null
}

("Might be" because this isn't free either; an approach like this is easier for caching, but requires at least one more round trip. Welcome to the world of tradeoffs.)

Cache is one of the important constraints in the REST architectural style; when you are designing your resource model, you should consider the implications of HTTP's standardized caching semantics.

1
  • Would it be a good approach to still keep the embedded representation, and instead remove the GET api/posts/1/header endpoint altogether from the REST API? (So basically forcing the consumer of the API to view the header as part of the Post) Apr 3, 2021 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.