Skip to main content

django-ninja-expose

Add @expose() to a Django model. Get a REST API.

from django.db import models
from django_ninja_expose import expose

@expose()
class Task(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)
# urls.py
from django.urls import path
from ninja import NinjaAPI
from django_ninja_expose import mount

api = NinjaAPI()
mount(api)  # or api.add_router("", get_router())

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

You get GET/POST /api/Task, GET/PUT/PATCH/DELETE/HEAD /api/Task/{pk}, Django-native filtering (?title__icontains=x&completed=false), Ninja pagination and OpenAPI docs.

Usage examples

The examples below use the Task model above, served at /api/Task (id is the auto-generated primary key).

GET — list and retrieve

List objects (paginated with Ninja's default LimitOffsetPagination):

GET /api/Task
// 200 OK
{
  "items": [
    {"id": 1, "title": "Write docs", "completed": false},
    {"id": 2, "title": "Ship release", "completed": true}
  ],
  "count": 2
}

Filter with Django lookups and paginate with limit / offset:

GET /api/Task?title__icontains=docs&completed=false&limit=10&offset=0
// 200 OK
{
  "items": [{"id": 1, "title": "Write docs", "completed": false}],
  "count": 1
}

Retrieve a single object:

GET /api/Task/1
// 200 OK
{"id": 1, "title": "Write docs", "completed": false}
// 404 Not Found (GET /api/Task/999)
{"detail": "Not Found"}

POST — create

POST /api/Task
Content-Type: application/json

{"title": "Write docs"}
// 201 Created
{"id": 1, "title": "Write docs", "completed": false}

Invalid data is rejected by Django's full_clean():

POST /api/Task
Content-Type: application/json

{"title": ""}
// 422 Unprocessable Entity
{
  "detail": [
    {"loc": ["body", "title"], "msg": "This field cannot be blank.", "type": "value_error"}
  ]
}

PUT — full update

PUT replaces the object: send every writable field (fields without a default are required).

PUT /api/Task/1
Content-Type: application/json

{"title": "Write better docs", "completed": true}
// 200 OK
{"id": 1, "title": "Write better docs", "completed": true}

PATCH — partial update

PATCH only changes the fields you send:

PATCH /api/Task/1
Content-Type: application/json

{"completed": true}
// 200 OK
{"id": 1, "title": "Write better docs", "completed": true}

DELETE

DELETE /api/Task/1
204 No Content

Deleting it again returns 404 Not Found with {"detail": "Not Found"}.

Calling the API from Python

import requests

base = "http://localhost:8000/api/Task"

task = requests.post(base, json={"title": "Write docs"}).json()
requests.patch(f"{base}/{task['id']}", json={"completed": True})
print(requests.get(base, params={"completed": "true"}).json())
requests.delete(f"{base}/{task['id']}")

@expose(path=None, methods=None, fields=None, query=None, auth=INHERIT, queryset=None)

None = automatic, [] = none, list = explicit restriction.

arg None [] list
path class name n/a URL path
methods all six (HEAD is never implied) no operations only these
fields all concrete fields + M2M no fields only these
query all exposed fields filtering disabled only these (subset of fields)

auth and queryset are separate: see Authentication and Object-level authorization.

Invalid configuration fails at import time (ExposeConfigurationError and subclasses); duplicate paths fail when the router is built.

Authentication

This library does not implement authentication. auth is passed straight to django-ninja, so you can use Ninja's built-in auth, Django's session auth, or your own.

auth value behaviour
INHERIT (default) use the auth of the NinjaAPI (or router) it is mounted on
None no authentication for this model, even if the API requires it
an auth object / callable use this auth for this model (e.g. django_auth, HttpBearer())
a list any one of them may authenticate (same as Ninja)
from ninja import NinjaAPI
from ninja.security import django_auth, HttpBearer
from django_ninja_expose import INHERIT, expose, mount

class Bearer(HttpBearer):
    def authenticate(self, request, token):
        if token == "secret":
            return token

@expose()                      # INHERIT: protected by the API-level auth below
class Task(models.Model): ...

@expose(auth=None)             # public, even though the API requires auth
class Tag(models.Model): ...

@expose(auth=Bearer())         # its own auth, overrides the API-level auth
class Invoice(models.Model): ...

@expose(auth=lambda request: request.user.is_staff or None)  # plain callable
class Report(models.Model): ...

api = NinjaAPI(auth=django_auth)
mount(api)

An unauthenticated request to a protected endpoint returns 401 Unauthorized. An invalid auth value raises InvalidAuthError at import time.

Object-level authorization

auth answers "who are you?". To decide which objects that user may touch, pass queryset, a callable (request, qs) -> qs:

from ninja.security import django_auth

def own_documents(request, qs):
    return qs.filter(owner=request.user)

@expose(auth=django_auth, queryset=own_documents)
class Document(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ...

The scoped queryset is the starting point of every operation, so:

  • list, filtering and pagination only see the user's rows;
  • get / put / patch / delete / head on someone else's object returns 404 (their existence is not leaked);
  • POST cannot be pre-filtered, so a created row that falls outside the scope is rolled back and rejected with 403 (e.g. creating a Document owned by another user).

Notes: request.user is only set if your auth sets it (django_auth does). If you do not want clients to choose the owner, leave it out of fields... but then it must be set some other way (e.g. a model default). PUT/PATCH may still move an object out of scope (e.g. change owner); exclude such fields from fields if that matters. A non-callable queryset raises InvalidQuerysetError at import time.

Security warning

@expose() exposes model data and CRUD operations by default. With auth=INHERIT it is only protected if your NinjaAPI (or router) has auth, so set NinjaAPI(auth=...). Also restrict methods, fields and query for production APIs.

Notes

  • Foreign keys and many-to-many fields are represented by primary keys (no nesting).
  • Filters accept Django lookups/transforms on whitelisted fields only; relationship traversal is rejected (HTTP 400).
  • Writes run Django's full_clean(); non-editable fields (e.g. auto_now_add) are never writable.

Metadata

Release files for django-ninja-expose 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-ninja-expose 0.1.2
File Size Uploaded Provenance Actions
django_ninja_expose-0.1.2.tar.gz 10.3 kB Without provenance Details for django_ninja_expose-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-ninja-expose 0.1.2
File Interpreter ABI Platform Actions
django_ninja_expose-0.1.2-py3-none-any.whl Python 3 none any Details for django_ninja_expose-0.1.2-py3-none-any.whl

Total release size: 24.7 kB

Release files / django_ninja_expose-0.1.2.tar.gz

Download URL django_ninja_expose-0.1.2.tar.gz
Size 10.3 kB
Tags Source
SHA-256 checksum
How to use checksums
74076a624dedbf8549d4795fec5ec77c3d0dab0367c694c0ff3468c1842becec
BLAKE2b-256 checksum
How to use checksums
64cf9e75e0281ff74623651e323a91340af8e9a077c739416aaf70c82681d752
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.0 {"installer":{"name":"uv","version":"0.12.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / django_ninja_expose-0.1.2-py3-none-any.whl

Download URL django_ninja_expose-0.1.2-py3-none-any.whl
Size 14.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8e16f5276d9d0d6c70c47563e00eed178670fe1d180d461671e41bc27abed14a
BLAKE2b-256 checksum
How to use checksums
6478ef2d3e499c02a664f10e4a86b5207de1d09d1d1f2f32df7fb569351b9109
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.0 {"installer":{"name":"uv","version":"0.12.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for django-ninja-expose 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page