DEV Community

Gias Uddin
Gias Uddin

Posted on • Updated on

4 step to built resful api using Django Rest Framework

If you are a web developer looking to build APIs, you might have heard about the Django Rest Framework (DRF). This powerful tool allows developers to quickly create APIs for their web applications using the popular Python-based web framework, Django.

In this blog post, we will be discussing how to build APIs using DRF. We will cover the following topics:

  1. Setting up DRF in your Django project
  2. Defining your API endpoints and models
  3. Configuring your API views and serializers
  4. Testing your API using the built-in browsable API feature

First, let's get started by setting up DRF in your Django project.

1.Setting up DRF in your Django project

To set up DRF in your Django project, you will need to install the package using pip. You can do this by running the following command in your terminal:

pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode

Once you have installed the package, you will need to add it to your project's list of installed apps in the settings.py file. To do this, simply add 'rest_framework' to the list of installed apps like so:

INSTALLED_APPS = [
    # Other installed apps
    'rest_framework',
]
Enter fullscreen mode Exit fullscreen mode

Now that you have installed and added DRF to your project, you are ready to start defining your API endpoints and models.

2.Defining your API endpoints and models

In DRF, API endpoints are represented as views, which are similar to regular Django views. To create an API view, you will need to create a new file in your project's views.py file and define a class that extends the DRF's APIView class.

For example, if you want to create an API endpoint for retrieving a list of users, you can create a view like this:

class UserListAPIView(APIView):
    def get(self, request, format=None):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)
Enter fullscreen mode Exit fullscreen mode

In this view, we are defining a get method that will handle HTTP GET requests. This method retrieves all the users from the database using the Django ORM and then serializes the data using a UserSerializer class. The serialized data is then returned as a response to the client.

Now that you have defined your API endpoint, you will need to define your models. In DRF, models are represented as classes that extend the DRF's ModelSerializer class.

For example, you can define a UserSerializer class like this:

class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name')
Enter fullscreen mode Exit fullscreen mode

In this serializer class, we are defining a Meta class that specifies the model and fields that should be serialized. In this case, we are using the User model and only serializing the id, username, email, first_name, and last_name fields.

3.Configuring your API views and serializers

Once you have defined your API endpoints and models, you will need to configure your views and serializers in the project's urls.py file.

To do this, you will need to import the views and serializers that you have define and add them to the project's URL patterns. For example, if you want to add the UserListAPIView to your project's URLs, you can do so like this:

from django.urls import path
from .views import UserListAPIView
from .serializers import UserSerializer

urlpatterns = [
    path('users/', UserListAPIView.as_view(), name='user-list')
]
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we are importing the UserListAPIView and UserSerializer classes and adding a new URL pattern that maps to the UserListAPIView. This URL pattern will be accessible at the /users/ endpoint.

Once you have added your views and serializers to the project's URLs, you are ready to test your API.

4.Testing your API using the built-in browsable API feature

DRF comes with a built-in browsable API feature that allows you to easily test your API and see the results in a friendly user interface. To enable this feature, you will need to add the DRF's DefaultRouter class to your project's urls.py file like so:

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'users', UserListAPIView, basename='user')

urlpatterns = [
    path('', include(router.urls)),
]
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we are creating a new DefaultRouter instance and registering our UserListAPIView with it. We are also specifying the URL pattern that the view should be mapped to (in this case, /users/).

Once you have enabled the browsable API feature, you can test your API by running the Django development server and navigating to the /users/ endpoint in your browser. You should see a friendly user interface that allows you to test your API and see the results.

In conclusion, building APIs using the Django Rest Framework is a straightforward and efficient process. By following the steps outlined in this blog post, you can quickly set up DRF in your Django project, define your API endpoints and models, configure your views and serializers, and test your API using the built-in browsable API feature.

Thank you for reading my article! If you enjoyed it and would like to support my work, please consider buying me a coffee at Buy Me a Coffee. You can also learn more about me and my work by visiting my Giasuddin Bio and following me on LinkedIn and Twitter. Thank you for your support!

Top comments (0)