简体   繁体   中英

REST API POST - Check if each nested object exists. If no, create new. If yes, return existing object

I'm somewhat new to RESTful API design practice and looking for help. The data model I'm working with details a top-level object (eg Book) containing a list of a nested objects (eg Chapters).
Each Chapter is persisted in its own right and has a simple_name field that is set to unique=True (ie. only one Chapter with Chapter.simple_name = "ch_01" may exist).

Scenario : A user POSTs a Book ("myBook_v1") containing Chapters, "ch_01", "ch_02", and "ch_03". The user then edits their book and the next day POSTs "myBook_v2" containing Chapters, "ch_01", "ch_02", "ch_03", and "ch_04" . Suppose that Chapters "ch_01", "ch_02", "ch_03" are unchanged from the original POST.

Currently, since simple_name is required to be unique, the second POST does not pass uniqueness validation and an error response is returned to the user.

Question : Would the following implementation fit REST design principles? And, most importantly, is this a good (safe) design choice?

Implementation : Upon Book POST, check each Chapter.simple_name for uniqueness. If Chapter.simple_name already exists in database, skip creation. If it does not exist, create new Chapter. Return complete persisted Book with a mix of newly created Chapters and already existing Chapters. The only criteria for deciding to create new or use existing is whether or not the user-specified simple_name already exists for a Chapter in the database.

这里的想法是通过删除关联的验证器来消除唯一性约束,然后自行处理添加/更新/删除(请参阅Django Rest Framework上的嵌套序列化程序的唯一验证 )。

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