django-rest-framework: Handling business logic and what to return?

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 09:18:22

问题


In my API a one can submit "Parent" with 1 child. This is the common use case. You always enter at least one child when entering parent. This is the same on the UI. There can be the case where the user will want to enter a duplicate parent, eg. it already exists in the system. In that case, in the UI, the user gets to choose if he indeed wants to add a duplicate or if he wants to add the child to one of the existing "duplicate" records. I hope this was clear enough.

My question is how I can do a similar "workflow" via the api? Upon submission of duplicate, it should return a list of possible existing entries to which child can be added. How should this list be returned? With what status code? (not really a client error)


回答1:


So your request looks something like:

POST /parents

{"name": "Foo", "child": { ... }}

And if "Foo" already exists, you require the client to choose an existing record and add the child there, correct? Then a response like this may be appropriate:

HTTP/1.1 409 Conflict

{
  "message": "Choose an existing parent.",
  "parents": [
    {"id": 1, ...},
    {"id": 2, ...},
    {"id": 42, ...}
  ]
}

This requires the client to repeat the request to something like:

POST /parents/42/children

{ ... }


来源:https://stackoverflow.com/questions/62444477/django-rest-framework-handling-business-logic-and-what-to-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!