Skip to main content

django-apiary

Typed API views in Django.

API Views

Apiary's APIView extends Django's generic View, with a few main differences:

  1. All parameters must be type-annotated.
  2. They automatically return JSON objects unless you return your own HttpResponse.
  3. Parameter values are assigned from the URL path parameters if applicable, then from the querystring for GET requests, and either POST or a JSON body for non-GET requests.
class AuthAPI(APIView):
    class Response(TypedDict):
        authenticated: bool
        token: NotRequired[str]

    def get(self, request: HttpRequest) -> Response:
        return self.Response(authenticated=False)

    def post(self, request: HttpRequest, username: str, password: str) -> Response:
        return self.Response(authenticated=True, token="authtoken")

The post method of this view could be called using form- or JSON-encoded data:

% curl -d 'username=admin&password=letmein' http://localhost:8000/api/v1/auth/

{"authenticated":true,"username":"admin","token":"authtoken"}

% curl -H 'Content-Type: application/json' -d '{"username":"admin","password":"letmein"}' \
    http://localhost:8000/api/v1/auth/

{"authenticated":true,"username":"admin","token":"authtoken"}

Parameter unpacking

Handlers may accept a single structured parameter (msgspec.Struct, dataclass, or TypedDict) whose fields are read directly from the querystring or request body when the parameter name does not otherwise appear in the data. For instance, the post handler above may be rewritten as:

class AuthParams(msgspec.Struct):
    username: str
    password: str


class AuthAPI(APIView):
    def post(self, request: HttpRequest, params: AuthParams) -> Response: ...

And calling it with either {"username":"admin","password":"letmein"} or {"params":{"username":"admin","password":"letmein"}} will work.

Note that while POST/PATCH/etc requests may specify multiple structured parameters, each read from their own key in the request body, GET and HEAD handlers may only specify a single structured parameter for unpacking.

Parameter aliases

Use Alias in an Annotated type to give a handler parameter a different external name:

from typing import Annotated
from apiary import Alias, APIView


class SearchAPI(APIView):
    def get(self, request, offset: Annotated[int, Alias("o")] = 0):
        return {"offset": offset}

Typed Headers

An APIView may define it's own inner Headers class as either a msgspec.Struct, dataclass, or TypedDict. Accessing self.headers will attempt to construct this type from request.headers, changing dashes to underscores in header names. Using msgspec.Struct allows you to specify the header name distinct from the attribute name in Headers.

class HeaderView(APIView):
    class Headers(msgspec.Struct):
        x_count: int
        enabled: bool = msgspec.field(name="X-Enabled")
        request_id: uuid.UUID = msgspec.field(
            name="X-Request-ID", default_factory=uuid.uuid4
        )
        x_optional: int | None = None

    # This ensures the type-checker knows about our Headers and not the default APIView.Headers
    headers: Headers

    def get(self, request: HttpRequest):
        return self.headers

Routing and middleware

Since APIView is a regular Django View subclass, you can use path or re_path like normal. But Apiary also comes with a lightweight middleware system that allows you to be a bit more declarative when defining your URL scheme. For instance:

from apiary import Route
from apiary.middleware import RequireAuth, Throttle

api_root = Route("api/v1/")(
    # Throttles requests for all children to 120 per minute.
    Throttle("120/min")(
        # Children may be API endpoints.
        Route("auth/", views.AuthAPI),
        # Or middleware. RequireAuth checks `request.user.is_authenticated`.
        RequireAuth(
            Route("issue/<int:issue_id>/", views.IssueAPI, name="api-v1-issue"),
            Route("search/", views.SearchAPI)(
                Route("<int:search_id>/", views.SavedSearchAPI),
            ),
        ),
        # RequireAuth can also take one or more permissions to check.
        RequireAuth("myapp.admin_perm")(
            Route("admin/", views.AdminAPI),
        ),
    ),
)

You can also define your own APIMiddleware (or Route, which is just a middleware that also yields URL patterns):

from apiary import exceptions
from .models import AccessToken


class AuthenticatedAPI(Route):
    def on_request(self, request: HttpRequest) -> HttpResponseBase | None:
        if not AccessToken.check_access(request):
            raise exceptions.AuthenticationFailed()

    def on_response(
        self, request: HttpRequest, response: HttpResponseBase
    ) -> HttpResponseBase | None:
        pass


api_root = AuthenticatedAPI("/api")(...)

RequireAuth

RequireAuth checks request.user.is_authenticated and raises AuthenticationFailed if the user is not authenticated. It may also accept a list of permissions to check; if the user does not have all the specified permissions, PermissionDenied is raised.

Throttle

By default, throttles with equivalent rate windows and bucket settings share usage per IP. Use scope to give identical policies independent quotas, for example Throttle("120/min", scope="search") and Throttle("120/min", scope="login"). Different policies always use separate cache entries, even with the same scope.

Regular (function) views

Apiary also provides an api_path function that can be dropped in for Django's path, and calls your function-based views with the same data sourcing and argument sematics as APIView:

def search_view(request: HttpRequest, query: str = "", limit: int | None = None): ...


from apiary import api_path

urlpatterns = [
    api_path("search/", search_view, name="search"),
]

OpenAPI

Apiary comes with an OpenAPIView that can render an OpenAPI specification for your API:

from apiary import OpenAPIView, api_endpoint

api_root = Route("api/v1/")(...)

urlpatterns = [
    api_root.to_urlpattern(),
    api_endpoint("openapi.json", OpenAPIView, route=api_root, title="Test API"),
]

Metadata

Release files for django-apiary 0.1.3

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-apiary 0.1.3
File Size Uploaded Provenance Actions
django_apiary-0.1.3.tar.gz 13.4 kB Without provenance Details for django_apiary-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-apiary 0.1.3
File Interpreter ABI Platform Actions
django_apiary-0.1.3-py3-none-any.whl Python 3 none any Details for django_apiary-0.1.3-py3-none-any.whl

Total release size: 29.0 kB

Release files / django_apiary-0.1.3.tar.gz

Download URL django_apiary-0.1.3.tar.gz
Size 13.4 kB
Tags Source
SHA-256 checksum
How to use checksums
a6c43902b8060b7c461ed54555971d4b78d8f3aabeed4296995e9b2e1419d764
BLAKE2b-256 checksum
How to use checksums
dca536a0a91113ea3758a0cd6f782f8552bc157be778ce35f97c2cbb248a5cb4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / django_apiary-0.1.3-py3-none-any.whl

Download URL django_apiary-0.1.3-py3-none-any.whl
Size 15.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3ec69e679ca3e65f846074ec7bb512e4fd72a5e2a49002456687783cbf3eadc2
BLAKE2b-256 checksum
How to use checksums
597d216a5929a53cc922866b98c6dd6cf729fec50d27d09ccf68ae462da628c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for django-apiary 0.1.3

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