I'm relatively new to REST, but I did my homework on how RESTful should be. Now I'm trying to create a RESTful api that implements the JSON + HAL serializer for my models that are related to other models.
Examples of models in 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)
suggests that we have a category “catalog” with a subcategory “food” with products “hamburger” and “hot dog” that are related to each other.
First question. Categories and products should be resources, so they need a URI, should I implement the uri field in my model and store it in the database or somehow calculate it at runtime, as for multiple identifiers (URIs)?
Second question. Openness, in Hal format, which should "GET /" and different nodes return so that the api can easily find itself.
{ "_links":{ "self":{ "href":"/" }, "categories":[ { "href":"/catalog" } ] } }
Third question. Add as properties, insert or link. Example "GET / 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", ... } ] } }
The fourth question. How hard I have to go, returning the structure. GET / catalog example
{ "_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": [] }