网页
综合
更新时间 2026-11-14 16:32:07
Quickstart - Django REST framework
自动蜘蛛
www.django-rest-framework.org
正文约 2837 字
We're going to create a simple API to allow admin users to view and edit the users and groups in the system.
Create a new Django project named tutorial, then start a new app called quickstart.
If you use Bash for Windows
The project layout should look like:
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).
Now sync your database for the first time:
We'll also create an initial user named admin with a password. We'll authenticate as that user later in our example.
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...
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.
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.
Right, we'd better write some views then. Open tutorial/quickstart/views.py and get typing.
Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.
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.
Okay, now let's wire up the API URLs. On to tutorial/urls.py...
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.
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.
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.
Pagination allows you to control how many objects per page are returned. To enable it add the following lines to tutorial/settings.py
Add 'rest_framework' to INSTALLED_APPS. The settings module will be in tutorial/settings.py
We're now ready to test the API we've built. Let's fire up the server from the command line.
We can now access our API, both from the command-line, using tools like curl...
Or using the httpie, command line tool...
Or directly through the browser, by going to the URL http://127.0.0.1:8000/users/...
If you're working through the browser, make sure to login using the control in the top right corner.
Great, that was easy!
If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。