API端点URL是否包含<id>?

时间:2019-01-07 11:51:52

标签: django rest django-rest-framework

推荐哪种方法?是否使用API​​端点URL?

/api/orders/<id>/

def post(self, request, id):
    order = get_object_or_404(Order, pk=self.kwargs.get('id'), company=request.user.company)
    ...

/api/orders/

def post(self, request):
    serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
             order_id = serializer.validated_data.get('order_id')
             order = Order.objects.get(pk=order_id)
             if order.user.company != request.user.company:
                 raise Http404
              .... 

2 个答案:

答案 0 :(得分:3)

这取决于您要实现的目标。

如果您尝试检索结果(即HTTP GET),则可以使用“ / api / orders”检索所有订单,并使用“ / api / orders / {id}”检索特定的订单。 / p>

另一方面,如果您尝试创建新订单(即HTTP POST),则可以使用“ / api / orders /”来创建新订单,并且在成功创建后,响应主体将返回订单对象(包括唯一ID)。

答案 1 :(得分:0)

Generally, we can use ListCreateAPIView class of DRF to List [GET] all the objects and Create [POST] a new object instance at some end-point like api/v1/orders/.

And to fetch/update/delete [GET/PATCH/DELETE] any single instance we can use RetrieveUpdateDestroyAPIView class of DRF hooked at some end-points of form api/v1/orders/<pk>/

Generally speaking end-points like api/v1/orders/ should list all available/applicable objects and appending <pk> to it should return details of object associated with that pk, otherwise handled properly with 404 or some other relevant status code.

My manager always used to refer me to this, so I would like to pass on the same; Do checkout https://developer.github.com/v3/

Reference :

https://www.django-rest-framework.org/api-guide/generic-views/#listcreateapiview https://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdatedestroyapiview