DEV Community

tobiadiks
tobiadiks

Posted on

2 1

Writing an API in Django (Class Based)

Rest API solve the problem of writing specific codes for different platform.
Django is a Python framework that supports the MVT and follows the DRY principle for writing codes.
To write API for your Django web app, here is how to go about it.

pip install django-rest-framework
Enter fullscreen mode Exit fullscreen mode

Go to your project setting.py and add rest_framework as an installed app.

[... ,
... ,
rest_framework,
... ,
]
Enter fullscreen mode Exit fullscreen mode

now we will create a new script called serializer.py in our app folder.
Open and add the following code

from rest_framework import serializers
from .models import model_name


class mySerializer(serializers.ModelSerializer):
    class Meta:
        model = model_name
        fields = ['__all__']
Enter fullscreen mode Exit fullscreen mode

Brace up 😁, you are almost done with your API.

Next up,
In views.py write the code below

from rest_framework.generics import ListCreateAPIView
from .serializer import mySerializer
from .models import model_name

class listApi(ListCreateAPIView):
    queryset = model_name.objects.all()
    serializer_class = mySerializer
Enter fullscreen mode Exit fullscreen mode

Lastly we are going to assign a URL to our API
open urls.py

from django.urls import path
from .views import listApi

urlpatterns = [path('api/list', listApi.as_view),
]
Enter fullscreen mode Exit fullscreen mode

open browser 127.0.0.1:8000

πŸŽ‰πŸŽ‰πŸŽ‰

You just made a Class Based API view.

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay