Debian Codegraph @

docs/tutorial/quickstart.md

raw
1 # Quickstart
2
3 We're going to create a simple API to allow admin users to view and edit the users and groups in the system.
4
5 ## Project setup
6
7 Create a new Django project named `tutorial`, then start a new app called `quickstart`.
8
9 === ":fontawesome-brands-linux: Linux, :fontawesome-brands-apple: macOS"
10
11 ```bash
12 # Create the project directory
13 mkdir tutorial
14 cd tutorial
15
16 # Create a virtual environment to isolate our package dependencies locally
17 python3 -m venv .venv
18 source .venv/bin/activate
19
20 # Install Django and Django REST framework into the virtual environment
21 pip install djangorestframework
22
23 # Set up a new project with a single application
24 django-admin startproject tutorial . # Note the trailing '.' character
25 cd tutorial
26 django-admin startapp quickstart
27 cd ..
28 ```
29
30 === ":fontawesome-brands-windows: Windows"
31
32 If you use Bash for Windows
33
34 ```bash
35 # Create the project directory
36 mkdir tutorial
37 cd tutorial
38
39 # Create a virtual environment to isolate our package dependencies locally
40 python3 -m venv .venv
41 source .venv\Scripts\activate
42
43 # Install Django and Django REST framework into the virtual environment
44 pip install djangorestframework
45
46 # Set up a new project with a single application
47 django-admin startproject tutorial . # Note the trailing '.' character
48 cd tutorial
49 django-admin startapp quickstart
50 cd ..
51 ```
52
53 The project layout should look like:
54
55 ```bash
56 $ pwd
57 <some path>/tutorial
58 $ find .
59 .
60 ./tutorial
61 ./tutorial/asgi.py
62 ./tutorial/__init__.py
63 ./tutorial/quickstart
64 ./tutorial/quickstart/migrations
65 ./tutorial/quickstart/migrations/__init__.py
66 ./tutorial/quickstart/models.py
67 ./tutorial/quickstart/__init__.py
68 ./tutorial/quickstart/apps.py
69 ./tutorial/quickstart/admin.py
70 ./tutorial/quickstart/tests.py
71 ./tutorial/quickstart/views.py
72 ./tutorial/settings.py
73 ./tutorial/urls.py
74 ./tutorial/wsgi.py
75 ./env
76 ./env/...
77 ./manage.py
78 ```
79
80 It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
81
82 Now sync your database for the first time:
83
84 ```bash
85 python manage.py migrate
86 ```
87
88 We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example.
89
90 ```bash
91 python manage.py createsuperuser --username admin --email [email protected]
92 ```
93
94 Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
95
96 ## Serializers
97
98 First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
99
100 ```python
101 from django.contrib.auth.models import Group, User
102 from rest_framework import serializers
103
104
105 class UserSerializer(serializers.HyperlinkedModelSerializer):
106 class Meta:
107 model = User
108 fields = ["url", "username", "email", "groups"]
109
110
111 class GroupSerializer(serializers.HyperlinkedModelSerializer):
112 class Meta:
113 model = Group
114 fields = ["url", "name"]
115 ```
116
117 Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
118
119 ## Views
120
121 Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
122
123 ```python
124 from django.contrib.auth.models import Group, User
125 from rest_framework import permissions, viewsets
126
127 from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
128
129
130 class UserViewSet(viewsets.ModelViewSet):
131 """
132 API endpoint that allows users to be viewed or edited.
133 """
134
135 queryset = User.objects.all().order_by("-date_joined")
136 serializer_class = UserSerializer
137 permission_classes = [permissions.IsAuthenticated]
138
139
140 class GroupViewSet(viewsets.ModelViewSet):
141 """
142 API endpoint that allows groups to be viewed or edited.
143 """
144
145 queryset = Group.objects.all().order_by("name")
146 serializer_class = GroupSerializer
147 permission_classes = [permissions.IsAuthenticated]
148 ```
149
150 Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
151
152 We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
153
154 ## URLs
155
156 Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
157
158 ```python
159 from django.urls import include, path
160 from rest_framework import routers
161
162 from tutorial.quickstart import views
163
164 router = routers.DefaultRouter()
165 router.register(r"users", views.UserViewSet)
166 router.register(r"groups", views.GroupViewSet)
167
168 # Wire up our API using automatic URL routing.
169 # Additionally, we include login URLs for the browsable API.
170 urlpatterns = [
171 path("", include(router.urls)),
172 path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
173 ]
174 ```
175
176 Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
177
178 Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
179
180 Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
181
182 ## Pagination
183
184 Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py`
185
186 ```python
187 REST_FRAMEWORK = {
188 "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
189 "PAGE_SIZE": 10,
190 }
191 ```
192
193 ## Settings
194
195 Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py`
196
197 ```text
198 INSTALLED_APPS = [
199 ...
200 'rest_framework',
201 ]
202 ```
203
204 Okay, we're done.
205
206 ---
207
208 ## Testing our API
209
210 We're now ready to test the API we've built. Let's fire up the server from the command line.
211
212 ```bash
213 python manage.py runserver
214 ```
215
216 We can now access our API, both from the command-line, using tools like `curl`...
217
218 ```bash
219 bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
220 Enter host password for user 'admin':
221 {
222 "count": 1,
223 "next": null,
224 "previous": null,
225 "results": [
226 {
227 "url": "http://127.0.0.1:8000/users/1/",
228 "username": "admin",
229 "email": "[email protected]",
230 "groups": []
231 }
232 ]
233 }
234 ```
235
236 Or using the [httpie][httpie], command line tool...
237
238 ```bash
239 bash: http -a admin http://127.0.0.1:8000/users/
240 http: password for [email protected]:8000::
241 $HTTP/1.1 200 OK
242 ...
243 {
244 "count": 1,
245 "next": null,
246 "previous": null,
247 "results": [
248 {
249 "email": "[email protected]",
250 "groups": [],
251 "url": "http://127.0.0.1:8000/users/1/",
252 "username": "admin"
253 }
254 ]
255 }
256 ```
257
258 Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`...
259
260 ![Quick start image][image]
261
262 If you're working through the browser, make sure to login using the control in the top right corner.
263
264 Great, that was easy!
265
266 If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide].
267
268 [image]: ../img/quickstart.png
269 [tutorial]: 1-serialization.md
270 [guide]: ../api-guide/requests.md
271 [httpie]: https://httpie.io/docs#installation