在Django REST Framework API Root 页面添加自定义函数 API 示例
首先,需要在'urls.py'中导入'DefaultRouter'和相关的view函数。例如:
from django.urls import path, include
from rest_framework import routers
from .views import MyAPIView
router = routers.DefaultRouter()
urlpatterns = [
path('', include(router.urls)),
path('my-api/', MyAPIView.as_view()), # 添加自定义的API视图
]
这里的'MyAPIView'是一个继承自'APIView'的自定义API视图。
接下来,在'views.py'中编写'MyAPIView'类:
from rest_framework.views import APIView
from rest_framework.response import Response
class MyAPIView(APIView):
def get(self, request):
data = {'message': 'Hello, World!'}
return Response(data)
这个视图类只是简单地返回一个JSON格式的消息。
最后,在项目的根URLconf中,将'rest_framework'的URL包含在其中:
from django.urls import path, include
urlpatterns = [
path('api-auth/', include('rest_framework.urls')),
path('my-app/', include('my_app.urls')),
]
这样,就可以在'http://localhost:8000/api-auth/'页面中看到Django REST framework的API浏览器,并在其中看到我们添加的自定义API视图。
原文地址: https://www.cveoy.top/t/topic/lo4H 著作权归作者所有。请勿转载和采集!