简体   繁体   中英

How to allow a user to create/update bulk data and be restful?

I'm creating a web API and I have a scenario where users will want to load a bunch of data in bulk, which would then be loaded into the database as multiple separate entries. This data could be brand new and thus created, or data may already exist and thus be updated. The definitions for POST and PUT seem to expect to work on only a single piece of data at a time, and the created status code reflects that in providing a location.

I already have methods that allow for a single piece of data to be created or updated. Should I write additional methods to facilitate the creation and updating of this bulk data or should I expect the user to make individual calls (perhaps hundreds of thousands of times) to load their data? What should I be returning as far as status codes and other data is concerned? Which request verbs should define these bulk calls?

The RESTful way to create multiple items inside a collection, is to use PUT on the whole collection.

This way you are making a request to replace the whole collection, so you need to pass both old and new items, but the new ones will be created by the server.

Suppose you had only one item in the /items collection called "old item". Here you request to update a collection so that it has two new items.

PUT /items

[{ Name: "old item"}, { Name: "new item 1"}, { Name: "new item 1"}]

You don't need to return any content inside a successful PUT response because success in this case means that the exact state you requested was applied. So it leaves status code 204.

And since you are updating a whole collection resource, you don't return 201 regardless of whether new items were created or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM