Skip to content

Repository files navigation

Restful-API-Example

This project is using Django and rest framework from python to build the news api for news agencies and news writers to use.

Table of Contents

Preparation

Install the R equirements

pip install -r requirements.txt

Add Super User

python manage.py createsuperuser

Run the Server

python manage.py runserver

To-Do List

  • Token authentication
  • Finish README.md
  • User registration
  • Password encryption

Functions Included

User Identification

For the User Identification, we need a database to store users' information, so creating a model in model.py is needed.

'''news/models.py'''classUserInformation(models.Model):
# The username for the users to sign inusername=models.CharField(max_length=32, unique=True)
# The password of the userpassword=models.CharField(max_length=64)
# The real name of the user, to be included in the news informationname=models.CharField(max_length=48, default='John Smith')

This will be used to store basic information of users

The authentication of users is mainly depend on the token. After users log in, the token will be stored into the database

'''news/models.py'''classUserTokens(models.Model):
# The token for the user, to be created after signing intoken=models.CharField(max_length=64)
# The user information from the UserInformation classuser=models.OneToOneField(to='UserInformation', on_delete=models.CASCADE)

The token is automatically generated and totally unique

The token generation is based on SHA-256 with the username and the login time

'''news/views.py'''deftoken_generate(user):
''' The token generation is based on SHA256 Parameters:  1. Username 2. Time (Keep the token unique) '''token=hashlib.sha256(bytes(user, encoding='utf-8'))
token.update(bytes(str(time.time()), encoding='utf-8'))
returntoken.hexdigest()

The user login with the payload of username and password, then the program will look up the information in the database

classLoginView(APIView):
# Only accept POST method in logindefpost(self, request, *args, **kwargs):
result= {'code': 200, 'msg': None}
try:
username=request._request.POST.get('username')
password=request._request.POST.get('password')
# Find the applicable user in the databaseuser=UserInformation.objects.filter(username=username, password=password).first()
result['msg'] ='Welcome, '+user.name+'!'ifnotuser:
result['code']=401result['msg']='Wrong Username or Password'else:
request.session["username"]=username# Generate the token for the usertoken=token_generate(username)
# Transfer the token to the user for identification useresult['token']=token# Add the token to the databaseUserTokens.objects.update_or_create(user=user, defaults={'token': token})
exceptExceptionase:
result['code']=401result['msg']='Bad Request'returnJsonResponse(result, status=result['code'])

If the user can successfully log in, the program will return a welcome message instead of 401 UNAUTHORIZED

News Lookup

Every one has the permission to lookup the news in the database
Firstly, the grant_permissionfunction helps to give GET request open to everyone

'''news/views.py'''defgrant_permission(self):
ifself.request.method=='GET':
# Everyone has the permission to find the newsself.permission_classes= [AllowAny]
else:
# The appending of the news can only happen after signing inself.permission_classes= [IsUserAuthenticated, SessionAuthenticated]

Secondly, the get method helps to load the choices and the return the search reasult

# Search newsdefget(self, request):
story_cat=request.data.get('story_cat', '*')
story_region=request.data.get('story_region', '*')
story_date=request.data.get('story_date', '*')
# Find the data with the conditions provided by the usersifstory_cat=='*':
stories=Story.objects.all()
else:
stories=Story.objects.filter(category=story_cat)
ifstory_region!='*':
stories=stories.filter(region=story_region)
ifstory_date!='*':
stories=stories.filter(date__gte=story_date)
# No news match the conditionifnotstories:
result= {'code': 404, 'result':'News Not Found'}
returnJsonResponse(result, status=result['code'])
# Use the serializer to output the resultserializer=StorySerializer(stories, many=True)
returnJsonResponse(serializer.data, status=200, safe=False)

News Modification

Append new stories

When appending new stories, users need to send a post request with the required information to the designated url which required to login first
So still need grant_permission method to switch the permission class

'''news/views.py'''defgrant_permission(self):
ifself.request.method=='GET':
# Everyone has the permission to find the newsself.permission_classes= [AllowAny]
else:
# The appending of the news can only happen after signing inself.permission_classes= [IsUserAuthenticated, SessionAuthenticated]

In the post method, the program will fetch all the data transferred in the request and append those into the database

'''news/views.py'''# Append newsdefpost(self, request, *args, **kwargs):
token=request._request.POST.get('token')
# Get the useruser=UserTokens.objects.filter(token=token).first().user.nameusername=UserTokens.objects.filter(token=token).first().user.usernametitle=request._request.POST.get('title')
category=request._request.POST.get('category')
region=request._request.POST.get('region')
details=request._request.POST.get('details')
try:
# Append the news into the databaseStory.objects.update_or_create(title=title,category=category,author=user,region=region,details=details,author_username=username)
result= {'code': 201, 'result':'News Posted'}
exceptExceptionase:
result= {'code': 404, 'result': 'Invalid Input'}
returnJsonResponse(result, status=result['code'])

News Agency Registration

About

Examples of News API for news agency using Django and Restful

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages