What is an APIView?

The Django REST framework offers a couple of helper classes we can use to create our API endpoints.

  1. APIView
  2. ViewSet

The APIView and The ViewSet both classes are slightly different and offer their own benefits in this post we will be diving in APIView.

The APIView is the most basic type of view we can use to build our API. It enables us to describe the logic which makes our API endpoint.

An APIView allows us to define functions that match the standard HTTP methods:

GET, POST, PUT, PATCH, DELETE

When to use APIViews?

  1. Need full control over logic.
  2. Processing files and rendering a synchronous response.
  3. Calling other APIs and Services.
  4. Accessing local files or data.

Now let's create our first APIView. First we are going to import some classes in our views.py.

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

Creating FirstAPIView Class.

Underneath the imports let's create a new class called FirstAPIView and inherit from the APIView which we imported from rest_framework.

class FirstAPIView(APIView):
    """ Test API View """

    def get(self, request, format=None):
        """ Returns some random values """
        py_list = [
            "apples","bananas",2,5
            ]

        return Response({'message': 'Hello!', 'list': py_list})

We created a get function which will return message and list as response if we receive GET request on this path.

Wiring it to URl.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('APP_NAME.urls')),
]

In above code we have made changes over boilerplate code such as:

  • Importing include function which helps us to include Urls from other apps.
  • Created new path api/ and wire it up with urls file of app.

Create new file in app folder as urls.py and paste below lines of code in it.

from django.urls import path
from APP_NAME import views

urlpatterns = [
    path('first-view', views.FirstAPIView.as_view()),
    ]

By adding above code we:

  • Imported path from django.urls and views from our custom app.
  • Created urlpatterns which linked first-view path to our FirstAPIView class.

Testing our APIView.

In terminal:

python manage.py runserver 0.0.0.0:8080

Visit below link using any browser:

127.0.0.1:8080/api/first-view/

Demo

31