231412 412389421
231412 412389421

Reputation: 313

API endpoint URL with <id> or without?

What approach is recommended? API endpoint URL with or without?

/api/orders/<id>/

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

or /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
              .... 

Upvotes: 0

Views: 977

Answers (2)

Umair Mohammad
Umair Mohammad

Reputation: 4635

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

Upvotes: 0

Mo A
Mo A

Reputation: 727

It depends on what you're trying to achieve.

If you're attempting to retrieve results (i.e. HTTP GET), then you could use "/api/orders" to retrieve all orders, and "/api/orders/{id}" to retrieve a specific order.

On the other hand, if you're trying to create a new order (i.e. HTTP POST), then "/api/orders/" can be used to create a new order, and upon successful creation, the response body will return the order object (including a unique ID).

Upvotes: 3

Related Questions