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)

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 is separate: see Authentication.

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.

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.1

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.1
File Size Uploaded Provenance Actions
django_ninja_expose-0.1.1.tar.gz 9.2 kB Without provenance Details for django_ninja_expose-0.1.1.tar.gz

Built distribution (wheel)

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

Total release size: 22.5 kB

Release files / django_ninja_expose-0.1.1.tar.gz

Download URL django_ninja_expose-0.1.1.tar.gz
Size 9.2 kB
Tags Source
SHA-256 checksum
How to use checksums
c134d3eab7612ad14c0b314ec0ff662fc3578f8bc9435072416491fab671f1bc
BLAKE2b-256 checksum
How to use checksums
7af2e03a4c864d56dde7e670e4149fa1f2f9871c09a4004aeba6adb12aa3cfed
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.1-py3-none-any.whl

Download URL django_ninja_expose-0.1.1-py3-none-any.whl
Size 13.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c005c9b1ed744bc4712ceb0d9ad304561432d437c1b211ea2168b3270f3e15a6
BLAKE2b-256 checksum
How to use checksums
bf758aa065c7a0a4c5b482f7d1bfc837fc5f29e1455cc50e734dd5098436706d
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.1

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