Skip to content

Quick Start (ModelSerializer)

Quick Start (ModelSerializer)

This guide shows how to create a CRUD API using ModelSerializer, which combines your Django model and serialization configuration in a single class.

Alternative Approach

If you prefer to keep your models unchanged and define serialization separately, see Quick Start (Serializer).

1. Create Your Model

Define your model using ModelSerializer with embedded serializer configuration:

Python
# models.py
from django.db import models
from ninja_aio.models import ModelSerializer


class Article(ModelSerializer):
    title = models.CharField(max_length=200)
    content = models.TextField()
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class ReadSerializer:
        fields = ["id", "title", "content", "is_published", "created_at"]

    class CreateSerializer:
        fields = ["title", "content"]
        optionals = [("is_published", bool)]

    class UpdateSerializer:
        optionals = [
            ("title", str),
            ("content", str),
            ("is_published", bool),
        ]

2. Create Your ViewSet

Define your API views using APIViewSet:

Python
# views.py
from ninja_aio import NinjaAIO
from ninja_aio.views import APIViewSet
from .models import Article

api = NinjaAIO(title="My Blog API", version="1.0.0")


@api.viewset(model=Article)
class ArticleViewSet(APIViewSet):
    pass

3. Configure URLs

Add the API to your URL configuration:

Python
# urls.py
from django.urls import path
from .views import api

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

4. Run Your Server

Bash
python manage.py runserver

Visit http://localhost:8000/api/docs to see your auto-generated API documentation!

Generated API Documentation

Endpoints Overview

Swagger UI Overview

Your API automatically includes:

Method Endpoint Description
GET /article/ List all articles (paginated)
POST /article/ Create new article
GET /article/{id} Retrieve single article
PATCH /article/{id}/ Update article
DELETE /article/{id}/ Delete article

List Endpoint

List Swagger

  • Automatic pagination
  • Query parameter filtering
  • Sorting support

Create Endpoint

Create Swagger

  • Input validation
  • Custom field support
  • Relationship handling

Retrieve Endpoint

Retrieve Swagger

  • Nested relationship serialization
  • Optimized queries

Update Endpoint

Update Swagger

  • Partial updates (PATCH)
  • Field-level validation
  • Custom actions

Delete Endpoint

Delete Swagger

  • Soft delete support
  • Cascade handling
  • Custom hooks

Next Steps

  • ModelSerializer Reference


    Deep dive into all ModelSerializer features

    Learn more

  • APIViewSet Features


    Custom endpoints, pagination, and filtering

    Explore

  • Authentication


    Add JWT authentication to your API

    Add auth

  • Full Tutorial


    Step-by-step guide covering all features

    Start tutorial