简体   繁体   English

设计REST API

[英]Design REST API

I'm designing API for my web application with django-REST, and frontend with Vue.js. 我正在使用django-REST设计Web应用程序的API,并使用Vue.js设计前端。 There are several "catalog" models. 有几种“目录”模型。 Each catalog item has id field and can have link field to other catalog item. 每个目录项都有ID字段,并且可以具有指向其他目录项的链接字段。 Here is example 这是例子

Device item 设备项

{
"id": 1,
"serial_num": "xxx",
"comment": "",
"nomenclature": 2,
"device_type": 3
}

Nomenclature item 命名项目

{
"id": 2,
"label": "HP probook 450",
}

Device_type item Device_type项

{
"id": 3,
"label": "Laptop",
}

Full label for Device item must be " device_type + nomenclature " = "Laptop HP probook 450". 设备项的完整标签必须为“ device_type + nomenclature ” =“ Laptop HP probook 450”。 So, when I need full label for Device item in frontend I must resolve fields "nomenclature" and "device_type", and then I get label. 因此,当我需要前端设备项的完整标签时,我必须解析字段“ nomenclature”和“ device_type”,然后才能获得标签。 But for each type of object I should make special function to resolve its label. 但是对于每种类型的对象,我应该使用特殊功能来解析其标签。 And hierarchy of objects can be much deeper. 对象的层次可以更深。

Maybe I should just add label field in Device object, which will assemble in backend. 也许我应该只在设备对象中添加标签字段,该标签字段将在后端组装。 What is the best practice? 最佳做法是什么?

Data representation is front end's job. 数据表示是前端的工作。 Your api's only job is to serve raw data to users with access as fast as possible. 您的api唯一的工作就是为具有访问权限的用户尽快提供原始数据。 That's why it's not great to have joined data in api answers. 这就是为什么在api答案中加入数据并不是很好。

Also you'll make your api bloated including fields that don't really belong to Device. 此外,您还将使api膨胀,包括不真正属于Device的字段。 Next time front end needs to update label format it will also trigger changes to api. 前端下次需要更新标签格式时,也会触发对api的更改。

But. 但。 If joining label to Device allows you to not expose Nomenclature and Device_type to api, ie decreasing number of needed http-calls by at least 2 every time, I think it's a good decision to allow retreiving label via Device endpoint (or rather just joining those objects into api response and still allowing front end to build label format by itself). 如果将标签连接到设备允许您不向api公开Nomenclature和Device_type,即每次至少减少2个所需的http调用,我认为这是一个很好的决定,允许通过Device端点检索标签(或者只是加入那些对象进入api响应,并且仍然允许前端自行构建标签格式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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