1

In my project, I have the following 4 APIs (function base API view)

save_user()
login_user()
get_user_info()
update_user()

I want to convert it into class base API view

class UserApi(APIView):

  def post():
    #save user
 
  def get(): 
    #for get user info

  def put():
    #for update user info


so how to use login() in class base views. OR use function base view for login?

to use a mixture of class based API view and function base API view in a single views.py file is good or bad?

1 Answer 1

3

To login, the user has to provide the username and password. This will be a HTTP post request. You can create a class-based view only for post for login and define the URL endpoint.

class Login(APIView):
   
    def post(self, request, format=None):
        # authentication related code

urlpatterns = [
    path('login/', Login.as_view()),
]

The main advantage of using class-based views is to separate the HTTP methods (get, post, put, delete) and write re-usable code. DRF provides generic class-based views that can be used for common functionality with less code.

For the login functionality, having a class-based view is useful if you have token based authentication. Since, you haven't mentioned about it, I would say having class-based views for both login and user will be good for consistency and readability. There is no rule that you can't mix class-based and function-based views; it depends on what you are trying to achieve and one is not necessarily good or bad over the other.

Sign up to request clarification or add additional context in comments.

1 Comment

class Login(APIView): having only one method or API is a good idea? What is the benefit of using class base API view instead of a function-based API view for the above example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.