Skip to content
Advertisement

Django Rest Framework With Only Function Response

I just want to make a simple API with DRF. The API going to get a “keyword” from URL, and that “keyword” will go to a function. And function response is going to be API response.

Simple Example:

def returnSomething(word):
    test_string = "This is a example sentence. "
    add_string = word
    test_string += add_string
    return test_string

http://127.0.0.1:8000/api/langdetect/helloworld/

RESULT:

{
  response: This is a example sentence. helloworld
}

It’s all easy. How can I make this? I read the doc but every example is making with Models, serializers etc. I don’t have any models. I have only a function and the response data.

Thanks.

Advertisement

Answer

You’ll want a bare APIView if you want to use DRF’s permissions and content type negotiation system yet still keep things simple:

from rest_framework.views import APIView
from rest_framework.response import Response

class SomethingView(APIView):
    def get(self, request, format=None):
        word = request.data.get('word')
        return Response({'response': f'Example: {word}'})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement