How to create Rest API without Django Rest Framework in pure Django?

How to create Rest API without Django Rest Framework in pure Django?

Can we build APIs, without DRF (Django Rest Framework)?

·

2 min read

Note: If you are looking for a Full Stack Developer (Django+React), then connect with me on LinkedIn or contact me through my portfolio.

Introduction:

Can we build APIs, without DRF (Django Rest Framework) 🤔 ?

DRF is to make things easy and comes with a lot of extra functionality which we don't even use sometimes.

If your goal is to just send some JSON data from your View response, then you do not need to go through all that hassle of setting up DRF.

Without wasting any time, let’s directly jump into the code:

Initial Steps:

Create a Django project named Demo, then create a Django app named api . Let’s further write our code.

Model:

Inside your api/models.py file, let’s create a Book model for this blog.

# api/models.py

from django.db import models

class Book(models.Model) :
    book_name = models.CharField(max_length=240)

Views:

Now, inside your api/views.py, we will create our View function to render the JSON data when requested from client side via an API call.

# api/views.py

from django.http import JsonResponse
from api.models import Book

def all_books_view(request):
    data = Book.objects.all()
    return JsonResponse(data)

def book_view(request, book_id):
    book = Book.objects.get(book_id=book_id)
    data = {
        book id: book.book_id,
        book_name: book.book_name,
    }
    return JsonResponse(data)

URLs:

We have to map our View function to the URLs inside our root urls.py file.

# demo/urls.py (Root urls.py file)

from diango.urls import path
from api.views import all_books_view, book_view

urlpatterns=[
    path("books/all/", all_books_view, name="all_books_view"),
    path("book/<int: book_id>/", book_view, name="book_view"),
]

Your APIs are done and ready to consume.

These are the endpoints which will return the desired results in JSON format when called from a client side.

PathDetail
/books/all/Will return all the books in a list.
/books/{ID}/Will return a single book as an object, for which you have to send a book ID in the URL.

For more such crispy blogs daily, follow DevJunction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!

Â