how to use same url and class for put, get, post, delete functions in drf class base api

Question:

in my views file I want to have this logic:

class Articles(APIView):

def get(self, reqeust, id):
    #logic
def put(self, request, id):
    #logic  
def post(self, requst, id):
    #logic
def delete(self, request, id):
    #logic

and I want handle urls like this :

/articles/int:pk # articles shows with id=pk
/articles/add # add article to db
and so on…

but I have problem that I don’t want to use different classes for different urls, and at the same time I want that if I call /articles/add , post method calls , what is the best way to implement this?

sry I’m very new to python and drf, I will be thanks to help me to do this in best way,

is the way I’m thinking to handle this totally wrong?
I just I don’t want to have different class in APIView approach using drf for every single post, get, … ones.

Asked By: Alireza

||

Answers:

but I have problem that I dont want to use different class and at the same time i want that if I call /articles/add post method call , what is the best way to implement this?

What you describe here already exists: that is a ViewSet [drf-doc]. This combines different methods all in the same class. Often, the same serializer, etc. are used. So it groups logic that is often very similar.

In order to then route the items correctly, a Router [drf-doc] is used to make the corresponding paths. Some are with the primary key, for example for GET, PUT, PATCH and DELETE, whereas POST does not have a primary key. You can further customize this then.

Answered By: willeM_ Van Onsem