-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject_info.txt
143 lines (101 loc) · 7.6 KB
/
project_info.txt
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
--------------- Project Intro ---------------
Video Ref: https://www.youtube.com/watch?v=B38aDwUpcFc
1. Setup the django-boilerplate.
2. Create an app & install it inside the project.
3. Install the django restframework at the top of all the apps using the following code.
INSTALLED_APPS = [
................,
'rest_framework',
'api_basics.apps.ApiBasicsConfig',
]
4. Inside the app create a model ('Article'). Register that model inside the 'admin.py' file.
#########################
[Serializer]: These allow complex data such as querysets and model instances to be converted
to native Python datatypes that can then be easily rendered into JSON, XML or other content types.
Serializers also provide deserialization, allowing parsed data to be converted back into complex types,
after first validating the incoming data.
#########################
[Class Serializer - not using]
5. Now create a serializer class for the newly created model inside a file called 'api_basics/serializers.py'.
When creating a serializer for a model, we need to define all the fields of that specific model inside the serializer-class.
[NB]: Instead of 'models.Xfield' use 'serializers.Xfield' inside the serializer-class.
6. Inside the model-serializer class, define the create, update func for the serializer-class.
7. For the update-func, we need to fetch & define all the fields through the validated_data. Store them inside the instance-fields after validation.
Assign the same name as the fields along with the "instance.fieldName".
Lastly, save the instance using the 'save()' function. Then return the instance also.
[Model Serializer]
8. Instead of using class-serializer, use the model-serializer, because it's more convenient to use (similar to django-forms).
[Function based API views]
9. Function-based API views are similar to regular function-based views. Try to keep separate the api-views in a new directory from the normal views.
In that file, import the following python packages.
from django.shortcuts import render
from django.http import HTTPResponse, JSONResponse
from rest_framework.parsers import JSONParser
from ..models import Article
from ..serializers import ArticleSerializer
from rest_framework.decorators import api_view # rest_framework decorator
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
[NB]: Since the func-based api_views are isolated in a different "api_views.py" file in a separated directory
inside the application & the "models.py" & the "serializers.py" files are 1-step upward, thus they need to be
imported with two dots ("..") preceding the fileNames.
########## @api_view(['Request Methods'])
10. Create a regular django function. Then just decorate the function with "@api_view()". An "@api_view([])" can contain both the 'GET', 'POST', 'PUT' & 'DELETE' request methods.
11. Define the urls accordingly in the app's 'urls.py' file.
12. For returning the serialized data, use the "Response" method to return 'serializer.data' by the end of the function.
13. Handle article-not-found-error inside the function to fetch a particular article.
[Class based API views]
14. Create a class based view ("ArticleAPIView") which contain the APIs responsible for displaying the articles-list also create a new article record.
Inside, there will be two methods ('get()' & 'post()') to accordingly enlist the articles & create a new article.
This class-based-view will be connected to a particular controller alias-named as "api_class_articleList".
15. Create another class-based-view ("ArticleDetail") which will be responsible for retrieve, update & delete a particular article-record.
Thus, inside this class, there will be a custom-func to fetch the specific article-record, & the rest of the "Retrieve", "PUT", "Delete" will use this function to execute the RUD operations.
The other funcs will accept the article-ID as an extra param.
The controller connected with this class-based-view is alias-named as "api_class_article".
[NB]: The 'get()', 'put()' & 'delete()' functions are meant to accept "id" as extra param, which makes their controller "api_class_article" take the 'id' as an extra param inside the URL-string.
[Note]: Each class-based-view extends the django's subclass "APIView" which provides the scope
of performing retrieve, post, put, delete operations in a single class, aiding to make the
code-base follow the DRY principle.
################### [ DONE ]
[ Error handling in the get, put, delete class-func for an article doesn't exist. ]
Scenario: If a user sent a particular article ID which doesn't exist, Django will throw an error.
In the class-based-view ("ArticleDetail") we've modified the "get()" func.
Implemented a condition to check the status-code, which will also wrapped up
with the "try-except" to make the "get()" func able to handle the 'article' object
as well which doesn't contain a status-code.
###################
[Generic API views]
Django’s "generic views" were developed as a shortcut for common usage patterns. They take
certain common idioms and patterns found in view development and abstract them so that you can
quickly write common views of data without having to repeat yourself.
Generic views make your code more DRY.
# The "genericView" class will extend the "generics.GenericAPIView" & "mixins" classes.
There are conventionally 5 mixins.
+ ListModelMixin
+ CreateModelMixin
+ RetrieveModelMixin
+ DestroyModelMixin
+ UpdateModelMixin
[Note]: If required, we can extend all the mixin classes inside that specific generic-class-view.
But we'll separate the Generic API views into 2 different classes.
01. One for displaying the Articles as a list & create new article-record.
02. Second one for retrieve, update, delete operations.
[Note]: Reason for separating the generic views is that one of the controller will mean to accept "id" as an extra parameter.
As consequence, if we place all the operations inside a single generic-api-view-class, then it's throwing an error due to "id" as an extra param.
Here, we'll use all the mixins as extended class.
16. Create one generic-view-class ("ArticleListGenericView") which will be responsible for displaying all the Articles and create new article-record.
This class will extend the "generics.GenericAPIView", "mixins.CreateModelMixin", "mixins.ListModelMixin".
Define the serializer_class & the queryset.
Define the "get()" & "post()" functions inside the class.
17. Create another generic-view-class ("ArticleGenericView") which will be responsible for retrieving, updating, deleting a specific article-record.
This class will extend "generics.GenericAPIView", "mixins.RetrieveModelMixin", "mixins.UpdateModelMixin", "mixins.DestroyModelMixin".
Define the serializer_class, the queryset & the lookup_field.
[Note]: for using the "lookup_field", we can build the controller which can accept "id" as an extra param.
Define the "get()", "put()" & "delete()" functions inside the class. These functions will also accept the id as an extra param.
[ IMPORTANT ]: The main magic happens while returning particular functions inherited from the mixins accordingly.
The mixins abstract all the codes & make the code-base DRY.
YT Timestamp ===> 42:13
YT Timestamp ===> 01:09:10 (Next: Class-based API views)
YT Timestamp ===> 01:24:53 (Next: Generic views & Mixins)
YT Timestamp ===> 01:40:42 (Next: Authentication)