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

Built distribution (wheel)

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

Total release size: 27.7 kB

Release files / django_apiary-0.1.1.tar.gz

Download URL django_apiary-0.1.1.tar.gz
Size 12.7 kB
Tags Source
SHA-256 checksum
How to use checksums
9354a02fca738a1e224bd3655ccf8993a0574dad9892cd238e2401c351020fb8
BLAKE2b-256 checksum
How to use checksums
9f6a71ba40f1f27a897a57fe5579b4708e9e6ed4502d613ec1cd9a0c10cbcf5e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.4 {"installer":{"name":"uv","version":"0.13.4","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.1-py3-none-any.whl

Download URL django_apiary-0.1.1-py3-none-any.whl
Size 15.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e6ee70b9837a370e4307041da546b3d9b166e7d026822bb4843d93a5856f9bd6
BLAKE2b-256 checksum
How to use checksums
abfb282fb166c1ed99d5d0d46fcad39e6e958a6fb18595effbae8f3a5d19e77a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.4 {"installer":{"name":"uv","version":"0.13.4","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.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