1. Settings
We created the Django Project tutorial, and the app QuickStart:
# Create a new Django Project Django-admin. # Use Virtualenvwrapper to create virtualenv# install Django and Django REST Framework # in Env tocreate a new app Python manage. PY Startapp QuickStart
Then set up the database according to your database configuration:
# tutorial/settings.pyDATABASES= { ' Default ': { ' ENGINE ': ' Django.db.backends.postgresql_psycopg2 ', ' NAME ': ' database_name ', ' USER ': ' Database_user ', ' PASSWORD ': ' Database_password ', ' HOST ': ‘‘, ' PORT ': ‘‘ } } ... Installed_apps = ( Span class= "pun" > ... ' QuickStart ' , Rest_ Framework ' : ( Rest_ Framework.permissions.IsAdminUser ' ' paginate_by ' : 10 }
Finally create a database from SYNCDB
Python manage. PY syncdb
2. Serialization
Next we create the code for the data serialization:
# quickstart/serializers.py FromDjango.Contrib.Auth.ModelsImport User, Group FromRest_frameworkImportserializersClass Userserializer(serializers.Hyperlinkedmodelserializer): Class Meta:Model= UserFields= (' URL ', ' Username ', ' email ' , ' Groups ' ) class Groupserializer (serializers. Hyperlinkedmodelserializer class meta: model =group fields = ( ' URL ' , ' name '
It is worth noting that we are using Hyperlinkedmodelserializer. You can use a primary key or other relationship, but using Hyperlinkedmodelserializer is a good RESTful design.
3. Views
# quickstart/views.py FromDjango.Contrib.Auth.ModelsImport User, Group FromRest_frameworkImportViewsetsFromQuickStart.serializersImport Userserializer, Groupserializer Class Userviewset(Viewsets.Modelviewset): "" "allows viewing and editing of user's API endpoint" "Queryset= User.objects. () Serializer_class =userserializer class Groupviewset (viewsets. Modelviewset "" "allows viewing and editing of group API endpoint" " Queryset = group.objects. () Serializer_class =groupserializer
In django_rest_framework, all common behaviors are attributed to viewsets. Of course we can split these behaviors, but use viewsets to make the view logic clearer.
Using Queryset and Serializer_class instead of model variables allows us to better control API behavior, which is the recommended way to use it.
4. URLs
# tutorial/urls.py FromDjango.Conf.URLsImportPatterns,Url,IncludeFromRest_frameworkImportRoutersFromQuickStartImportViews Router=Routers.Defaultrouter()Router.Register(R' Users ',Views.Userviewset)Router.Register(R' Groups ',Views.Groupviewset) # wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. Urlpatterns = Patterns ( ", Url (r ' ^ ' , Include (router< Span class= "pun". urls Url (r ' ^api-auth/' , Include ( ' rest_framework.urls ' , namespace= ' rest_framework '
Because we are using viewset, we can use the route class to automatically generate the URL conf.
5. Testing
Now that our setup is complete, we can test our REST API and start the Django server first:
./Manage. PY Runserver
We can use the Curl command:
Bash:Curl-H' Accept:application/json; Indent=4 ' -U admin:Password http:127.0.0.1:8000/users/ { "Count": 2, "Next": Null, "Previous": Null, "Results": [ { "Email": "[Email protected]", "Groups": [], "url": "Http://127.0.0.1:8000/users/1/", "Username": "Admin" }, { : "[email protected]" , "groups" : [], "url" : " http://127.0.0.1:8000/users/2/", " username " : "Tom" }] } /span>
Or you can use the browser directly:
Django-rest-framework Tutorial: Quick Start