Create APIs in Django REST Framework Without @api_view Decorator
There are several ways to create an API without using the '@api_view' decorator in Django REST Framework. Here are a few examples:
- Using class-based views:
from rest_framework.views import APIView
from rest_framework.response import Response
class MyAPI(APIView):
def get(self, request):
# your code here
return Response(data)
- Using function-based views:
from rest_framework.decorators import api_view
from rest_framework.response import Response
def my_api(request):
if request.method == 'GET':
# your code here
return Response(data)
my_api = api_view(['GET'])(my_api)
- Using routers:
from rest_framework import routers, serializers, viewsets
class MySerializer(serializers.ModelSerializer):
# your serializer code here
class MyViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MySerializer
router = routers.SimpleRouter()
router.register(r'my_api', MyViewSet)
Note that in the third example, the '@api_view' decorator is not used because the router automatically generates the necessary views and URLs for the API.
原文地址: https://www.cveoy.top/t/topic/mXBI 著作权归作者所有。请勿转载和采集!