我对 REST 比较陌生,但我一直在做关于 RESTful 应该如何做的功课。现在我正在尝试为与其他模型有关系的模型创建一个实现 JSON+HAL 序列化程序的 RESTful api。
python中的示例模型:
class Category(Model):
name = CharField()
parent = ManyToOneField(Category)
categories = OneToManyField(Category)
products = ManyToManyField(Product)
class Product(Model):
name = CharField()
price = DecimalField()
related = ManyToManyField(Product)
categories = ManyToManyField(Category)
假设我们有一个类别“目录”,其中包含一个子类别“食物”,其中的产品“汉堡”和“热狗”都是相关的。
第一个问题。类别和产品应该是资源,因此它们需要一个 URI,我应该在我的模型中实现一个 uri 字段并将其存储在数据库中还是以某种方式在运行时计算它,多个标识符(URI)呢?
第二个问题。可发现性,在 Hal 格式中,“GET /”和不同的节点应该返回什么以使 api 易于自我发现。
{
"_links":{
"self":{
"href":"/"
},
"categories":[
{
"href":"/catalog"
}
]
}
}
第三个问题。添加为属性、嵌入或链接。示例“获取 /catalog/food”:
{
"_links":{
"self":{
"href":"/catalog/food"
}
},
"name":"food",
"parent":"/catalog",
"categories":[],
"products":[
"/products/burger",
"/products/hot-dog"
]
}
{
"_links":{
"self":{
"href":"/catalog/food"
},
"parent":{
"href":"/catalog"
},
"categories":[
],
"products":[
{
"href":"/products/burger"
},
{
"href":"/products/hot-dog"
}
]
},
"name":"food"
}
{
"_links":{
"self":{
"href":"/catalog/food"
}
},
"name":"food",
"_embedded":{
"parent":{
"_links":{
"self":{
"href":"/catalog"
}
},
"name":"catalog",
...
},
"categories":[
],
"products":[
{
"_links":{
"self":{
"href":"/products/burger"
}
},
"name":"burger",
...
},
{
"_links":{
"self":{
"href":"/products/hot-dog"
}
},
"name":"hot-dog",
...
}
]
}
}
第四个问题。返回结构时我应该走多深。示例“获取/目录
{
"_links":{
"self":{
"href":"/catalog"
}
},
"name":"catalog",
"parent":null,
"categories":[
{
"name":"food",
"parent":{...},
"categories":[],
"products":[
{
"name":"burger",
"price":"",
"categories":[...],
"related":[...]
},
{
"name":"hot-dog",
"price":"",
"categories":[...],
"related":[...]
}
]
}
],
"products": []
}