Skip to main content

Django API Decorator

A collection of tools to build function based Django APIs.

Warning This project is still in early development. Expect breaking changes.

Installation

Django API Decorator can be installed from PyPI:

uv add django-api-decorator

Or, without uv: pip install django-api-decorator

Usage

The main interface of this library is the @api decorator. This handles input and output from your view, according to type annotations on the view. Pydantic is used to handle most of the encoding and decoding, but you are not limited to use pydantic models for your types. You can use any type supported by pydantic, from simple types to dataclasses and typed dicts.

Here's a simple example:

@api(method="GET")
def list_some_numbers(request: HttpRequest) -> list[int]:
    return [1, 2, 3, 4]

Under the hood the @api decorator will encode the list of numbers ot JSON and wrap it up in a response object for Django to handle like any other response.

You can also specify query parameters, that will be decoded according to the specified type annotations:

@api(method="GET", query_params=["count"])
def list_some_numbers(request: HttpRequest, count: int) -> list[int]:
    return [random.randint(0, 10) for _ in range(count)]

Here the decorator will extract the count query paramter from the request and make sure it's a valid integer.

The decorator can also decode the request body for you:

@api(method="POST")
def sum_of_numbers(request: HttpRequest, body: list[int]) -> int:
    return sum(body)

The views produced by the decorator are plain Django views and should be added in your urls module just like any other view:

urlpatterns = [
    path("/api/numbers/", list_some_numbers, name="list-some-numbers"),
]

If you want to handle multiple methods on the same url a method_router helper function is provided, which can be used like this:

urlpatterns = [
    path(
        "/api/numbers/",
        method_router(
            GET=list_some_numbers,
            POST=...
        ),
        name="list-some-numbers",
    ),
]

OpenAPI specification

This library can also generate an OpenAPI specification from your views. This is done by inspecting the urlpatterns of the Django project, finding all views using the @api decorator. The schema for the specification is generated using pydantic, so for details about how different types are treated see Pydantic's documentation.

The specification is generated using the generate_api_schemas management command.

Control Operations Included in the Schema

Controlling which operations are included in the generated schema can be useful. Your application might depend on libraries that also use the django-api-decorator package to build APIs, and you may prefer not to include those in your schema.

This is achieved by defining a set of tags on each view method.

@api(method="GET", tags=["django-api-decorator"])
def view(request: HttpRequest) -> None:
    ...

Views without the tags property set will always be included in the schema.

You can either exclude tags you don't want in your schema or select tags you want to include. However, you cannot both include and exclude tags simultaneously.

Including Tags in the Schema

Specify the tags to include in your schema in the Django settings file:

API_DECORATOR_SCHEMA_INCLUDE_TAGS = ["app", ...]

Excluding Tags from the Schema

Specify the tags to exclude from your schema in the Django settings file:

API_DECORATOR_SCHEMA_EXCLUDE_TAGS = ["library", ...]

Generate schema by alias

By default the schema is generated by alias. This means that the schema will use the aliases defined in the model_config property of the pydantic model.

You can disable this by setting the API_DECORATOR_GENERATE_SCHEMA_BY_ALIAS setting to False.

Setting root level servers in the OpenAPI specification

OpenAPI servers docs

You can set the servers in the Django settings file:

API_DECORATOR_SERVERS = {
    "servers": [{"url": "https://api.example.com"}],
}

The servers are added to the OpenAPI specification as a list of dictionaries with the a requried url and optional description.

Metadata

Release files for django-api-decorator 1.0.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-api-decorator 1.0.3
File Size Uploaded Provenance
django_api_decorator-1.0.3.tar.gz 14.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-api-decorator 1.0.3
File Interpreter ABI Platform
django_api_decorator-1.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 32.4 kB

Release files / django_api_decorator-1.0.3.tar.gz

Download URL django_api_decorator-1.0.3.tar.gz
Size 14.1 kB
Tags Source
SHA-256 checksum
How to use checksums
f26d8cf2a47ccfb4f4682aebc8af1d8681bb32b389ee57dfac590b42af6fcf86
BLAKE2b-256 checksum
How to use checksums
f2c09817a215261468db65de5cf01f78c7c19068a26d9bbbf75cd1151249e30d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.10 {"installer":{"name":"uv","version":"0.12.10","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_api_decorator-1.0.3-py3-none-any.whl

Download URL django_api_decorator-1.0.3-py3-none-any.whl
Size 18.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9f364b851a1ffdcaaa907e85c45fde879710fb8871bbdc18a5136719086d1e4f
BLAKE2b-256 checksum
How to use checksums
e5bbc779888c967c6d63add05b9ed5c46e867108222566fe873c395a405bef51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.10 {"installer":{"name":"uv","version":"0.12.10","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-api-decorator 1.0.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