ChatterBot Django Views

Example API Views

ChatterBot’s Django example comes with an API view that demonstrates one way to use ChatterBot to create an conversational API endpoint for your application.

The endpoint expects a JSON request in the following format:

{"text": "My input statement"}
class ChatterBotApiView(View):
    """
    Provide an API endpoint to interact with ChatterBot.
    """

    chatterbot = ChatBot(**settings.CHATTERBOT)

    def post(self, request, *args, **kwargs):
        """
        Return a response to the statement in the posted data.

        * The JSON data should contain a 'text' attribute.
        """
        input_data = json.loads(request.body.decode('utf-8'))

        if 'text' not in input_data:
            return JsonResponse({
                'text': [
                    'The attribute "text" is required.'
                ]
            }, status=400)

        response = self.chatterbot.get_response(input_data)

        response_data = response.serialize()

        return JsonResponse(response_data, status=200)

    def get(self, request, *args, **kwargs):
        """
        Return data corresponding to the current conversation.
        """
        return JsonResponse({
            'name': self.chatterbot.name
        })

Note

Looking for the full example? Check it out on GitHub: https://github.com/gunthercox/ChatterBot/tree/master/examples/django_app