About Lesson
In this Django REST Framework we are going to learn Django REST Framework API View Decorator, you can use decorators with function api based view, for example you can use api_view(), the core of this functionality is the api_view
decorator, which takes a list of HTTP methods that your view should respond to. also using this decorator you can access to django browsable api view.
Now we are going to change views.py functions like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
from .models import Article from .serializers import ArticleSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status # Create your views here. @api_view(['GET', 'POST']) def article_list(request): """ List all articles, or create a new article. """ if request.method == 'GET': articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def article_details(request, pk): """ Retrieve, update or delete article. """ try: article = Article.objects.get(pk=pk) except Article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ArticleSerializer(article) return Response(serializer.data) elif request.method == 'PUT': serializer = ArticleSerializer(article, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': article.delete() return Response(status=status.HTTP_204_NO_CONTENT) |
This is our urls.py file.
1 2 3 4 5 6 7 8 |
from django.urls import path from .views import article_list, article_details urlpatterns = [ path('articles/', article_list), path('articles/<int:pk>/', article_details) ] |
If you go to http://localhost:8000/articles/ you can see a browsable api from the django rest framework with same functionality of posting article, getting article, retrieving article, deleting article and updating article.