How to make Restful Login API in python

Posted By : Rajat khurana | 08-Apr-2017

Hi everyone, 
Here you learn how to create a restful API in Django. For making a login API in Django , you need to use Django authentication system , which will authenticate username and password from database. To use Django authentication system, you need to import this:

from django.contrib.auth import authenticate

From mporting this, you used authenticate function of Django auth module . See in code this line:


    userobj = authenticate(username=uname, password=passw);

This line give authenticate username and password .  To make a Login API in Python you need to create a class in handler.py and import different module you can use in API. Here is example of class :

class LoginHandler(BaseHandler):
"""
Interface  for login API
TODO: remove target fields
"""
model = User
allowed_methods = ('POST',)

@staticmethod
def resource_uri():
    return ('api3_login_handler', [])

@log_request
def create(self, request):
    """
    Returns authentication token
    """
    try: data = simplejson.loads(request.raw_post_data)
    except:
        msg = {'message':"Username or Password Not Present", 'response':  { 'user' : " " } }
        return sendResponse("BAD_REQUEST",msg)

    uname = data.get('username', '')
    passw = data.get('password', '')

    if(uname == ""):
        msg = {'message':"The server did not understand the request",'status': "BAD_REQUEST", 'response':  { 'user' : " " } }
        return sendResponse("BAD_REQUEST",msg);

    if(passw == ""):
        msg = {'message':"The server did not understand the request",'response':  { 'user' : " " } }
     return sendResponse("BAD_REQUEST",msg);

    userobj = authenticate(username=uname, password=passw);
    if user is None:
         error = True;
         msg = { 'error': error, 'message':"Authentication Failed", 'response':  { 'user' : " " }  , 'status': "BAD_REQUEST", }
         return sendResponse("FORBIDDEN",msg)
    else:
            unique_token = uuid.uuid4()
            unique_token = str(unique_token);
            error = False
            profile = {}
            profile["id"] = userobj.id
            profile["token"] = unique_token;
            profile['username'] = userobj.uname;
            profile['useremail']= user_email;
            message = { 'error': error, 'message':"Authentication Successfully", 'response': { 'user' : profile } , 'status': "ACCEPTED", }
            return sendResponse("ALL_OK",message)
 
 
 
After creating class, url-mapping is done in url.py and mapping is done on basis of Handler. Here LoginHandler is name of class. Remeber you need to import all model in url.py also. Here send Response id function which send the response in json format.
 
Related Tags

About Author

Author Image
Rajat khurana

Rajat is a bright Javascript Developer, he has good knowledge of HTML, WordPress, NodeJs, Core Java, Javascript, Jquery. Apart from this he loves to play Badminton and PC Gaming.

Request for Proposal

Name is required

Comment is required

Sending message..