There are several ways to create an API without using the '@api_view' decorator in Django REST Framework. Here are a few examples:

  1. 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)
  1. 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)
  1. 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.

Create APIs in Django REST Framework Without @api_view Decorator

原文地址: https://www.cveoy.top/t/topic/mXBI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录