0
0
Djangoframework~5 mins

APIView for custom endpoints in Django

Choose your learning style9 modes available
Introduction

APIView lets you create your own special web addresses that do exactly what you want. It helps you control how your app talks to others.

You want to make a new web address that does something unique not covered by default views.
You need to handle different actions like GET, POST, PUT, DELETE in one place.
You want to customize how data is received and sent in your app.
You want to add special checks or rules before doing something.
You want to return custom messages or data formats.
Syntax
Django
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class MyCustomView(APIView):
    def get(self, request):
        # code to handle GET request
        return Response({'message': 'Hello, GET!'}, status=status.HTTP_200_OK)

    def post(self, request):
        # code to handle POST request
        data = request.data
        return Response({'received': data}, status=status.HTTP_201_CREATED)

Each method (get, post, put, delete) matches an HTTP action.

Use Response to send data back to the user.

Examples
This example shows a simple GET method that returns a greeting message.
Django
class HelloView(APIView):
    def get(self, request):
        return Response({'greeting': 'Hi there!'})
This example echoes back whatever data was sent in a POST request.
Django
class EchoView(APIView):
    def post(self, request):
        return Response({'you_sent': request.data})
This example handles both GET and DELETE methods with different responses.
Django
class MultiMethodView(APIView):
    def get(self, request):
        return Response({'method': 'GET'})
    def delete(self, request):
        return Response({'method': 'DELETE'}, status=204)
Sample Program

This view keeps a simple count. GET shows the current count. POST increases the count by one and returns it.

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

class SimpleCounterView(APIView):
    count = 0

    def get(self, request):
        return Response({'count': self.count})

    def post(self, request):
        SimpleCounterView.count += 1
        return Response({'count': SimpleCounterView.count}, status=status.HTTP_201_CREATED)
OutputSuccess
Important Notes

APIView does not connect to URLs automatically; you must add it to your URL patterns.

State like count in the example is shared across requests and users, so use with care.

Use serializers to validate and clean data before processing.

Summary

APIView lets you write your own rules for web requests.

You define methods like get() and post() to handle different actions.

Use Response to send back data and status codes.