What is the proper RESTful API method to replace an entire collection?
Asked Answered
C

3

5

Imagine, We have an Entity School and this entity has a one to many relationship with Student entity. In other words, there is a collection of Students attached to a given School

If we are to replace the entire Student collection via a single API call,

API_URL/school/:school_id/students

which is the best Rest method to go along with. I think PUT is only used on an Entity not on a Collection. Hence, available options would be to use either PATCH or POST

Cup answered 11/12, 2017 at 12:35 Comment(0)
T
5

I think PUT is only used on an Entity not on a Collection

No - PUT is used on a resource, not on an entity or collection.

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.

The changes that happen to the entities in your domain are a side effect of the manipulation of REST resources. See Jim Webber's talk REST: DDD in the Large.

If your message body is a replacement representation for the resource, then either POST or PUT is the appropriate method to use

If your message body is a patch document, then you should use POST or PATCH.

If you are concerned that POST would be overloaded, then create a new resource in your design to manage this part of your integration protocol.

Again, heed Jim Webber:

URIs do NOT map onto domain objects - that violates encapsulation. Work (ex: issuing commands to the domain model) is a side effect of managing resources. In other words, the resources are part of the anti-corruption layer. You should expect to have many many more resources in your integration domain than you do business objects in your business domain.

Trantham answered 11/12, 2017 at 13:21 Comment(0)
D
1

I'm facing same issue. My teammates hate none resource nouns in the path. So in order to pass the API design review and to distinct an operation on whole collection from one on a single resource, I go one level up to the school.

GET /schools/1234

{ "schoolMetadat": "xxxx", "students": [] }

And PATCH on the students property. An update to a property is always replacement.

Driven answered 15/10, 2022 at 1:3 Comment(1)
please don't answer questions with issues but with solutions, you should comment the post insteadMelville
L
0

For updating the entire resource use PUT, for partial update use PATCH.

PATCH API_URL/school/:school_id {students: [...]}
PUT API_URL/school/:school_id/students [...]
PATCH API_URL/school/:school_id/students {add: [...], remove: [...]}

And don't confuse web services in the presentation layer with ORMs in the data access layer.

Lamont answered 15/10, 2022 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.