Python Forum
[Django] Build Fast, Type-Safe APIs with Django Ninja – Full Guide + CRUD Example
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Django] Build Fast, Type-Safe APIs with Django Ninja – Full Guide + CRUD Example
#1
Star 
If you're working with Django and want to build fast, clean, and modern APIs, Django Ninja is a powerful tool worth exploring. It brings FastAPI-like speed and type safety, while staying fully integrated with Django.



What is Django Ninja?

Django Ninja is a lightweight web framework for building APIs using Django and Python type hints. It uses Pydantic for data validation and provides automatic Swagger documentation out of the box.

It’s built on top of FastAPI’s ideas, but tailored for Django developers.



Key Features
  • [] Full support for Python type hints
    [] Fast API development with minimal boilerplate
    [] Built-in request validation using Pydantic
    [] Auto-generated interactive docs (Swagger UI)
    [] Supports both sync and async views
    [] Easy integration with Django ORM



Django Ninja vs DRF – Quick Comparison
  • [] Speed: Django Ninja is faster out of the box.
    [] Type Hints: Full support in Django Ninja, limited in DRF.
    [] Learning Curve: Easier with Django Ninja, DRF can be more complex.
    [] Async Support: Django Ninja supports async natively.
  • Swagger Docs: Built-in with Django Ninja, requires setup in DRF.



Quick Start

1. Install Django Ninja
pip install django-ninja
2. Create a basic API
from ninja import NinjaAPI

api = NinjaAPI()

@api.get("/hello")
def hello(request):
return {"message": "Hello from Django Ninja!"}
3. Add to urls.py
from django.urls import path
from .views import api

urlpatterns = [
path("api/", api.urls),
]
4. Visit Swagger Docs: http://localhost:8000/api/docs



CRUD Example: Book API

models.py
from django.db import models

class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
published_year = models.IntegerField()
schemas.py
from ninja import Schema

class BookIn(Schema):
title: str
author: str
published_year: int

class BookOut(BookIn):
id: int
views.py
from ninja import NinjaAPI
from .models import Book
from .schemas import BookIn, BookOut
from django.shortcuts import get_object_or_404

api = NinjaAPI()

@api.post("/books", response=BookOut)
def create_book(request, data: BookIn):
book = Book.objects.create(**data.dict())
return book

@api.get("/books", response=list[BookOut])
def list_books(request):
return Book.objects.all()

@api.get("/books/{book_id}", response=BookOut)
def get_book(request, book_id: int):
return get_object_or_404(Book, id=book_id)

@api.put("/books/{book_id}", response=BookOut)
def update_book(request, book_id: int, data: BookIn):
book = get_object_or_404(Book, id=book_id)
for attr, value in data.dict().items():
setattr(book, attr, value)
book.save()
return book

@api.delete("/books/{book_id}")
def delete_book(request, book_id: int):
book = get_object_or_404(Book, id=book_id)
book.delete()
return {"success": True}
urls.py
from django.urls import path
from .views import api

urlpatterns = [
path("api/", api.urls),
]


Final Thoughts

If you’re already using Django and want a cleaner, faster way to build APIs with full type safety and auto docs, Django Ninja is a solid option. It blends perfectly with the Django ecosystem while offering modern Python practices.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Basic] Ultimate Guide to Data Types BlazingWarlord 2 5,725 May-26-2021, 04:44 PM
Last Post: Gribouillis
Information Beginner's Guide to Pie Charts with Python BlazingWarlord 0 2,467 May-16-2021, 07:30 AM
Last Post: BlazingWarlord
  Easy Guide For GUI + Database Work adnanahsan 1 3,069 Sep-08-2019, 02:19 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020