我有一个简单的CRUD应用程序,有许多关系,我负责编写后端编程,包括数据库,业务逻辑和API调用。访问我的API的唯一一个是具有AJAX调用的前端,并且前端需要了解数据模型。我一直在调用这个REST但是经过研究这个问题已经意识到我没有做“真正的REST”(我也不关心)。我只想创建最有效,最直观,最美观的API来实现这些目标。 为包含多对多关系的CRUD应用设计URI,请求和响应的最佳方法是什么,仅由前端使用?
以下是我提出的一般设计。这些使用示例表Foo
和Bar
,它们之间有多对多的关系。联结表是FooBar
。即,
Foo ---< FooBar >--- Bar
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
URL: /api/foo/<id>
Method: GET
Request: empty
Response: {"data": {"id": 1, "name": "fizz"}}
URL: /api/foo/
Method: POST
Request: {"data": [{"name": "fizz"}, ...]}
Response: {"data": [{"id": 1, "name": "fizz"}, ...]}
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.
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.
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.
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.
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.
URL: /api/foo
Method: PUT
Request: {"data": [{"id": 1, ...}, ...]}
Response: {"data": {}}
Notes: I'm not sure what to return here.
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.