Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of API written with Django REST framework

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article is about using Django REST framework to write API example analysis, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, say no more, follow the editor to have a look.

Django is tied to the front and rear by default, and provides Template and Form. Now the front and rear separation project is popular, and the boss of Python can no longer sit still, so there is Django REST framework: https://github.com/tomchristie.

Official website: https://www.django-rest-framework.org/

Django REST framework (DRF for short) is the back-end framework of the Python technology stack, which is used to build RESTful API.

RESTful API

REST, which means REpresentational State Transfer, has an excellent explanation of what RESTful is:

Look at URL and you'll know what you want.

Look at Method and you'll know what to do.

If you look at Status Code, you can see what the result is.

The basic principles of good RESTful API design are:

Return to JSON

Misuse of status codes is strictly prohibited

Deal with paging

Return specific entity data instead of generic JSON data

Request object has default value

Create a project

Next we use DRF to create a simple API that allows administrators to view and edit users and groups.

First create a project named tutorial and an app named quickstart:

# create project directory mkdir tutorialcd tutorial# create Python virtual environment python-m venv env# activate virtual environment env\ Scripts\ activate.bat # Mac use `source env/bin/ activate` # install Django and Django REST frameworkpip install djangopip install djangorestframework# in virtual environment to create project. Note that there is a "." at the end, which means to create django-admin startproject tutorial .cd tutorial# to create appdjango-admin startapp quickstartcd..

The created directory structure is as follows:

$pwd/tutorial$ find... / manage.py./tutorial./tutorial/__init__.py./tutorial/quickstart./tutorial/quickstart/__init__.py./tutorial/quickstart/admin.py./tutorial/quickstart/apps.py./tutorial/quickstart/migrations./tutorial/quickstart/migrations/__init__.py./tutorial/quickstart/models.py./tutorial/quickstart/tests.py./tutorial/quickstart/views.py./tutorial/settings.py./tutorial/urls.py./tutorial/wsgi.py

Generally, app is not put into project. This is to avoid naming conflicts.

Then synchronize the database:

Python manage.py migrate

Then create a super administrator with the password password123:

Python manage.py createsuperuser-email admin@example.com-username adminSerializers

Serialization refers to the conversion of the database model to JSON. Create a new module tutorial/quickstart/serializers.py:

From django.contrib.auth.models import User, Groupfrom rest_framework import serializersclass UserSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url',' username', 'email',' groups'] class GroupSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url',' name'] Views

The view is used to accept the Web request and return the Web response. Open tutorial/quickstart/views.py and add the code:

From django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom rest_framework import permissionsfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializerclass UserViewSet (viewsets.ModelViewSet): "API endpoint that allows users to be viewed or edited." Queryset = User.objects.all () .order_by ('- date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet (viewsets.ModelViewSet): "" API endpoint that allows groups to be viewed or edited. "" Queryset = Group.objects.all () serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] URLs

Configure routing, open tutorial/urls.py, and add code:

From django.urls import include, pathfrom rest_framework import routersfrom tutorial.quickstart import viewsrouter = routers.DefaultRouter () router.register (rushing userslists, views.UserViewSet) router.register (rushing grouppers, views.GroupViewSet) # Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [path ('', include (router.urls)), path ('api-auth/', include (' rest_framework.urls', namespace='rest_framework'))]

Because you are using viewsets instead of view, you can generate URLconf for API automatically by registering class.

You can also use view instead of viewsets, and then customize API URL.

Pagination

Paging is used to control how much data is returned per page, adding to tutorial/settings.py:

REST_FRAMEWORK = {'DEFAULT_PAGINATION_CLASS':' rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10} Settings

In tutorial/settings.py, add 'rest_framework' to the

INSTALLED_APPS:INSTALLED_APPS = [... 'rest_framework',] Test API

Start the project:

Python manage.py runserver

Visit http://127.0.0.1:8000/users/ and click on the upper right corner to log in with hypertube, and you can see:

Finally fixed the problem of copying and pasting from the blog park to the automatic line wrapping of the official account code block without scrollbars. F12 only knew that a style had been overwritten, and this sentence was done:

# topics .PostBody pre {white-space: pre! important;} above is the example analysis of writing API in Django REST framework. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report