Configure Django Rest Framework with Django Project

Intermediate 10 minutes Aug. 29, 2025

Don't just build websites—build platforms! This Blog is a deep dive into the essentials of setting up Django REST Framework (DRF). You'll learn the secret to creating a clean, scalable API layer for your Django applications. I’ll break down the configuration process step-by-step, showing you how to go from a standard Django project to an API powerhouse. Whether you're building a mobile app backend or a single-page application, this is the first step you need to take.

Want to build APIs with Django? This Blog shows you how to quickly configure Django REST Framework (DRF) and get started with API development.

The Ultimate Guide to Building a REST API with Django REST Framework

Welcome! If you're looking to build powerful, scalable APIs with Django, you've come to the right place. In this guide, we'll walk you through the essential steps to configure Django REST Framework (DRF) and create a robust API from scratch. Whether you're a beginner or an experienced Django developer, this tutorial will help you get started with one of the most popular tools in the Django ecosystem.

Why Use Django REST Framework?

Before we dive into the "how," let's quickly touch on the "why." Django is fantastic for building web applications, but when it comes to creating an API, DRF is a game-changer. It takes the heavy lifting out of API development by providing:

  • Serializers: Effortlessly convert complex data types, like Django querysets and model instances, into native Python data types that can be easily rendered into JSON or XML.
  • Authentication & Permissions: Built-in systems to secure your API endpoints.
  • Browsable API: A fantastic web interface that makes it easy to test and interact with your API directly from your browser.
  • Comprehensive Tooling: A wide range of generic views, routers, and pagination tools that save you from writing repetitive code.

In short, DRF helps you build APIs faster and more efficiently.

Step 1: Install and Configure Django REST Framework

Before we dive in, if you're looking to get your development environment ready, or if you just want to make sure you're starting with a clean slate, you can find a helpful guide on our blog that walks you through setting up Python and a new Django project.

First, let's get DRF set up in your Django project.

  1. Installation: Open your terminal and install the package using pip:
python
pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

2. Configuration: Next, open your settings.py file and add rest_framework to your INSTALLED_APPS:

python
# myproject/settings.py

INSTALLED_APPS = [
    # ... your existing apps
    'rest_framework',
]

If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file.

This single line tells Django to include DRF's functionality in your project.

python
urlpatterns = [
    # ... your existing apps
    path('api-auth/', include('rest_framework.urls'))
]

3. Next step in any DRF project is to set up your global API settings. All of these are kept in a single dictionary called REST_FRAMEWORK within your main settings.py file. Go ahead and add the following code to get started:

python
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.AllowAny",
    ],
}

This is your central hub for configuring everything from authentication to pagination, ensuring a consistent approach across your entire API. We'll add more to it as our project grows, but for now, this is where it all begins.

Step 2: Create a Django "Post" App

Now, let's create a new Django app to hold our API's logic. This is where we will define our data model for posts.

python
python manage.py startapp post

Don't forget to add this new app to your INSTALLED_APPS in settings.py.

Now that we've created our post app, we need to let our main Django project know that it exists. This is a crucial step for Django to recognize the new app and its models.

Open your main settings.py file and find the INSTALLED_APPS list. Simply add the name of our new app, 'post', to this list:

python
# myproject/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework', # Our previously added DRF
    'post',         # <--- Add your new app here
]

By adding 'post' to this list, we've successfully linked our new app to the project, allowing it to be recognized by commands like makemigrations and migrate, before need to create models.

If you haven't run migrate on your project yet, To ensure your project has all the default tables it needs to function, you'll want to run the following command:

bash
python manage.py migrate

This command will apply the initial migrations that come with Django, setting up the tables for things like user authentication, sessions, and the admin panel.

Step 3: Create a Model for the Post

Open post/models.py and define the structure for our Post model. For this example, we'll keep it simple with a title, content, and an author.

python
# post/models.py
from django.db import models

# Create your models here.
class postModel(models.Model):
    title = models.CharField(max_length=100)
    cont = models.TextField()

    def __str__(self):
        return self.title

After creating the model, run makemigrations and migrate to create the corresponding table in your database.

Step 4: Run Migrations

To get our database ready, we need to run the initial migration command.

python
python manage.py makemigrations
python manage.py migrate

This will create all the necessary database tables for the Django framework.

The makemigrations command inspects your Django project's models.py files for any changes you've made (like adding or deleting a model, or changing a field). It then packages these changes into a migration file. This file is essentially a set of instructions that tells Django how to modify the database schema to match your models. It doesn't actually change the database yet; it just creates the blueprint for those changes. migration file are available migrations folder under post folder.

The migrate command applies the changes from the migration files to the database. It reads the migration files created by makemigrations and executes the SQL commands necessary to create, modify, or delete database tables and columns. Django keeps track of which migrations have been applied, so you can run this command as many times as you want without accidentally applying the same changes more than once. It's the command that actually makes the changes happen in your database.

Step 5: Create a Serializer for the Post Model

A serializer is the heart of DRF. It's responsible for converting our Post model instances into data types that can be sent over the wire, and vice-versa. Create a new file post/serializers.py and add the following code:

python
# post/serializers.py
from rest_framework import serializers
from .models import postModel

class postSerializer(serializers.ModelSerializer):
    class Meta:
        model = postModel
        fields = ["id", "title", "cont"]

Using ModelSerializer is a huge time-saver as it automatically generates the fields and validation logic for you.

Step 6: Create API Views

This is where we'll define the logic for handling HTTP requests. We'll use function-based views for this example to handle GET (retrieve) and POST (create) requests. Open post/views.py and add the following:

python
# post/views.py
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
from .models import postModel
from .serializer import postSerializer
from rest_framework import status

# Create your views here.
@api_view(http_method_names=["GET", "POST"])
def postViews(request: Request):
    allData = postModel.objects.all()
    serializer = postSerializer(allData, many=True)
    if request.method == "POST":
        data = request.data
        serializer = postSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            resData = {"message": "Post Created", "data": serializer.data}
            return Response(data=resData, status=status.HTTP_201_CREATED)
        return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    return Response(data=serializer.data, status=status.HTTP_200_OK)

We use the @api_view decorator to tell DRF what HTTP methods our function can handle and to provide the browsable API.

Step 7: Create URL Endpoints

Now, we need to connect our view to a URL. First, create a urls.py file inside the post app and add the following:

python
# post/urls.py
from django.contrib import admin
from django.urls import path, include
from .views import postViews

urlpatterns = [
path("post/", postViews, name="api_post"),
]

Finally, include this new URL configuration in your project's main urls.py file.

python
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('post.urls')), # Our API endpoint
    # ... rest of your urls
]

Step 8: Testing the API with the Browsable API

Start your development server:

python
python manage.py runserver

Now, navigate to http://127.0.0.1:8000/api/post/ in your browser. You'll be greeted by DRF's stunning browsable API!

  • GET Request: You'll see a JSON representation of all the posts in your database.
  • POST Request: At the bottom, you can use the form to create a new post. Simply enter the title, content, and author, and hit the "POST" button. If successful, you'll see the new post returned in the response.

Congratulations! You've successfully configured Django REST Framework and built your first API endpoints. This is just the beginning of what you can do with DRF. From here, you can explore class-based views, viewsets, and more to build even more complex and powerful APIs.

Happy coding!

Do You Need Side Hustle?<<<<<<<<

Earn Cash for Your Opinions and a Bonus to Boot: Try Respondent.io

Respondent is a top platform that pays you for taking part in market research and user interviews. I've used it to find great paid studies, and you can, too. Their referral program is a fantastic way to earn more: when a friend you refer signs up and completes a study, you both get a bonus. It’s a great way to earn a little extra for yourself while helping a friend find paid work.

Click here to sign up and get your bonus!

Disclaimer: Referral bonus amounts and terms are subject to change by Respondent.io. The bonus is typically awarded after the referred friend completes their first paid study. Please check their official referral program page for the most up-to-date details.


Get Paid to Share Your Opinion: User Interviews Can Get You Quick Cash

Ever heard of User Interviews? It's a platform that pays you for your feedback on products and services. The best part is that you can get a bonus just for signing up and completing your first study. I've already earned money with them, and you can, too.

Click here to sign up and get your bonus! Please wait until Sign Up page load.

Disclaimer: Referral bonus amounts are subject to change. The bonus is awarded after you complete your first paid study and may take a few days to process. All terms and conditions are set by User Interviews, and it's best to check their official site for the most up-to-date program rules.