具有多对多关系的CRUD应用程序的httpapi设计

2024-04-20 11:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

TL;DR

我有一个简单的CRUD应用程序,有很多对多关系,我负责编写后端,包括数据库、业务逻辑和API调用。唯一访问我的api的是带有AJAX调用的前端,前端应该了解数据模型。我一直称之为休息,但在研究了这个问题后,我意识到我没有做“真正的休息”(我也不在乎)。我只想创建最有效、最直观、最漂亮的API来实现这些目标。为包含多对多关系的CRUD应用程序设计uri、请求和响应的最佳方法是什么,这些关系仅由前端使用?

要求

  1. API必须能够在同一HTTP调用中接收多个对象以进行优化。你知道吗
  2. Foo应该在同一个HTTP调用中创建并关联到Bar(反之亦然,原子地。这就排除了前端在一个调用中创建Foo,并在下一个调用中将其关联到Bar的可能性。你知道吗

我当前的设计

下面是我提出的总体设计。它们使用示例表FooBar,它们之间有多对多关系。连接表是FooBar。即

Foo ---< FooBar >--- Bar

阅读所有Foos

URL: /api/foo
Method: GET
Request: empty
Response: {"data": [{"id": 1, "name": "fizz"}, ...]}
Notes: There isn't a way to read only some specified number
       of foos, as GET doesn't take a Request

按ID读取一个Foo

URL: /api/foo/<id>
Method: GET
Request: empty
Response: {"data": {"id": 1, "name": "fizz"}}

创建Foo

URL: /api/foo/
Method: POST
Request: {"data": [{"name": "fizz"}, ...]}
Response: {"data": [{"id": 1, "name": "fizz"}, ...]}

创建一个Foo并将其关联到一个酒吧

URL: /api/foo/
Method: POST
Request: {"data": [{"bar_id": 123, "name": "fizz"}, ...]}
Response: {"data": [{"id": 1, "name": "fizz"}, ...]}
Notes: I know to associate this with a BAR due to the presence
       of a "bar_id" field. I'm not sure if I should also return
       the "foo_bar_id" of the junction table in this response.

将以前创建的Foo与条形图相关联

URL: /api/foo/
Method: POST
Request: {"data": [{"id": 1, "bar_id": 123}, ...]}
Response: {"data": {}}
Notes: I know this is a previously created Foo due to the presence
       of a "id", and to associate it to a Bar due to "bar_id".
       I'm not sure if I should return the "foo_bar_id" of the junction
       table in this response.

删除Foo和Bar之间的关联

URL: /api/foo
Method: POST
Request: {"data": [{"id": 1, "bar_id": 123}, ...]}
Response: {"data": {}]
Notes: I know to delete the association rather than the Foo due to 
       the presence of the "bar_id". I'm not sure what to return here.

删除N Foos

URL: /api/foo/
Method: DELETE
Request: {"data": [{"id": 1}, ...]}
Response: {"data": {}}
Notes: Unlike GET, I can specify the number of Foos to delete.
       I'm not sure what to return here.

删除一个Foo

URL: /api/foo/<id>
Method: DELETE
Request: empty
Response: {"data": {}}
Notes: I don't really want to encourage the front end to 
       delete Foos one at a time. I'de rather disable this.

更新N Foos

URL: /api/foo
Method: PUT
Request: {"data": [{"id": 1, ...}, ...]}
Response: {"data": {}}
Notes: I'm not sure what to return here.

更新1 Foo

URL: /api/foo/<id>
Method: PUT
Request: {"data": {"id": 1, ...}}
Response: {"data": {}}
Notes: I don't really want to encourage the front end to 
       update Foos one at a time. I'de rather disable this. 
       I'm not sure what to return here.

Tags: ofthetoapiidurldatafoo