Can I use POST or PUT rest endpoints to create or update list of items? or These should be always deal with single resource object?
URL: POST/cars
request body:
{
[ {id:car1}, {id:car2}, {id:car3} ]
}
If I pass list of resources to these endpoints, how I can deal with exception scenarios on creating or updating specific a particular item in the resource list?
It is ok to send list of items (rather than single item) to update to PUT endpoint?
CodePudding user response:
It's not recommended to use POST or PUT to create a list of resources. Even if you want to update/create a list then you can pass the resource which represents a list.
like the below with a URL like URL: POST/dogs
{
"id": "dogs",
"dogs": [{
"id": "dog1"
},
{
"id": "dog2"
},
{
"id": "dog3"
}
]
}
to update a specific item you could use PATCH and also PUT is to update the entire resource.
CodePudding user response:
Can I use POST or PUT rest endpoints to create or update list of items? or These should be always deal with single resource object?
The requests in the HTTP application target a specific resource. But there really aren't any important restrictions on the semantics of the representations that you send, or how many resources the server might create/modify in response to your request.
Consider creating a new entry in a wiki - you type a bunch of information into a web form, and submit a single POST request, and the server copies your information and suddenly there's a new topic page, and a discussion page for that topic, and maybe a history of edits page, and so on.
Or if I had a JSON document that was my shopping list, and I wanted that list to be available on my website, then I could just PUT/POST the entire list as a single document; here you go.
That said, cache invalidation can get complicated. The cache invalidation semantics of HTTP are pretty limited, so if an HTTP request changes many resources that the client has cached locally, you won't have an easy way to signal to a general purpose web cache that they should all be invalidated.
It's not right or wrong -- the cache invalidation rules just a constraint you should think about when you are designing things.