Getting Started with Django Rest Framework (DRF): A Beginner’s Guide
Muhammad Abu Bakar
Software Engineer || Python || Django || React || Full Stack Developer
In the past few days, I was learning DRF. how to implement API in Django using DRF. First of all, I learned the essential method function based to implement API but then I learned different methods of how you could build API in Django. In this, I learned
- Class-Based
- Function Based
- Generic API View And Mixins
- Concrete View Class
- ViewSet
- Model View Set
- Basic Authentication And Permission
- Session Authentication And Permission
- JWT
- Throttling
- Filtring
- Pagination
- Nested Serializer
When we talk about class-based API it works absolutely the same but is built with the class-based method.
Class-Based View
class Student(GenericView,TemplateView): template_name = ‘student.html’ def get(self,request): return render(request,self.template_name)
this is the way through which you can write your class-based view.
Some people Prefer to write Function based view. I also prefer to write a function-based view but we need to perform some extra tasks in the function in which a class-based view is already provided in it. if you import any class you don’t need to perform Django ORM queries extra in your code.
Here is an example of Function Based View
def student_detail(request): students = Student.objects.all() serializer = StudentSerializer(students,many=True) print(serializer.data) return HttpResponse(JSONRenderer().render(serializer.data),content_type=’application/json’)
Here we can see that we are properly performing a query where we are getting student data from the database to show it on the browser. If we do it on a class-based we don’t need to perform some of these tasks. We can extend the generic class to CreateAPIView, ListAPIView, DestroyAPIView, and others(Concrete View Class).
Model ViewSet
If you are using viewset in your Django views you just need to import viewset in your file and add this piece of code to your views. Then you just need to slightly change your URL file
class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all()
add this viewset to your file. for this viewset you need to change your URL file here are the changes you can do in your URL file you need to register the URL in your using router
router.register(‘singer’,views.UserViewSet,basename=’singer’)
Then you can add the URL path into urlpatterns like this urlpatterns = [ path(‘admin/’, admin.site.urls), path(‘api/’,include(router.urls)), ]
in this way your program works fine your root URL appeared on 127.0.0.1:8000/api/
and through here you can access the different URLs which you registered in the routers
When we Talk about only Viewset we just import viewset class and use it into our class to use its functionality for CRUD operation here is a small example of how we can utilize Viewset
class SingerViewSet(viewsets.ViewSet):
For Getting all the Data
def list(self, request): queryset = Singer.objects.all() serializer = SingerSerializer(queryset, many=True) return Response(serializer.data)
For Creating Data
def create(self, request): serializer = SingerSerializer(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)
For Getting specfic Data
def retrieve(self, request, pk=None): queryset = Singer.objects.all() singer = get_object_or_404(queryset, pk=pk) serializer = SingerSerializer(singer) return Response(serializer.data)
For Updating Data
def update(self, request, pk=None): singer = Singer.objects.get(pk=pk) serializer = SingerSerializer(singer, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
For Deleting Data
def destroy(self, request, pk=None): singer = Singer.objects.get(pk=pk) singer.delete() return Response(status=status.HTTP_204_NO_CONTENT)
this is how you can use a view set to perform crud operation.
Basic Authentication and Session Authication
The authentication in Django is used to authenticate the user who is accessing our Django app. if we use basic authentication we just add basic authentication in our class and it’ll ask for your username and password on the other hand session-based authentication is based on the session. If a user is signed in it will generate an id for that user until the user gets logged out. The user session ended
Json Web Token
There is another time type of authentication we called token authentication in which JWT is used. through JWT users can authenticate can be logged in to the site and can log in to the site using third parties app.
Throttling & Filtring &Pagination
First, we’ll talk about the concept of throttling. in throttling, we limited someone's access to our data. like if we are using someone's data and they say that you can use our API only 5 times a day and you can modify our API only two times a day. this concept is called throttling. We restrict people's requests to our API to certain numbers.
For this purpose, we need to add this code to our settings.py
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } }
This describes that anonymous users can access our data only 100 times a day and user access data 1000 times a day. this can apply when we have security problems
Then we have a concept of Filtring. for filtering data we can use basic Django SQL queries and use a basic operation like ordering, and start with. using such operations we can optimize our code using Django DRF.
The next step is pagination. if our API is so large that we need to scroll it to access the data. we can use this concept. this concept is really handy because it converts your data into pages and you can handle the data easily.
Nested Serializer
Our Last concept was a Nested serializer. For example, if we have two classes of serializer we can use the first class in the second easily instead of creating a new field and we use the previous class. For this, we have some built-in classes in Django that makes our work easy.
Graphic designer
1 年sir your software house is I want to learn python. And want to take physical classes...?
Développeur d'applications | ReactJS | nextjs | react native Je crée des applications web , mobile , des sites web, J'accompagne les entreprises et particuliers dans la maintenance de leurs systèmes.
1 年Your messages are blocked
Développeur d'applications | ReactJS | nextjs | react native Je crée des applications web , mobile , des sites web, J'accompagne les entreprises et particuliers dans la maintenance de leurs systèmes.
1 年Good morning Mr. Please can I dm you? Because I have problem with create custom model user. Since yesterday.