Skip to main content

Use type annotations for request validation and serializer fields in Django REST Framework

Project description

Django REST - Typed

Package version Python versions Python versions PyPI - Django Version

This project extends Django REST Framework to allow use of Python's type hints for automatically validating view parameters, as well as supporting typed attributes and annotation-generated fields on serializers.

Deriving automatic behavior from type annotations has become increasingly popular with the FastAPI and Django Ninja frameworks. The goal of this project is to provide these benefits to the DRF ecosystem.

Main benefits:

  • View inputs can be individually declared, not buried inside all-encompassing request objects.
  • Type annotations can replace repetitive view validation/sanitization code.
  • Simple serializers can have their fields auto-generated from annotations
  • Validated serializer data can be accessed from attributes, with their types known to the IDE
  • Pydantic models and Marshmallow schemas are compatible types for view parameters. Annotate your POST/PUT functions with them to automatically validate incoming request bodies.

Documentation: https://rsinger86.github.io/drf-typed

Source Code: https://github.com/rsinger86/drf-typed

Views Example

from rest_typed.views import typed_api_view

"""
GET /users/registered/?registered_on=2019-03-03&staff=yes
"""

@typed_api_view(["GET"])
def get_users(registered_on: date = None, staff: bool = None):
    print(registered_on, is_staff)
    # date(2019, 3, 3) True
    data = query_orm(registered_on, is_staff)
    return Response(data)

Serializers Example

from datetime import date
from rest_typed.serializers import TSerializer


class MovieSerializer(TSerializer):
    title: str          # same as: CharField(required=True, allow_null=False)
    release_date: date  # same as: DateField(required=True, allow_null=False)
    description = None  # same as: DateField(default=None)

movie = MovieSerializer(data={
  "title": "The Last Duel",
  "release_date": "2021-10-15",
})

movie.is_valid(raise_exception=True)

print(movie.validated_data)
"""
  {
    "title": "The Last Duel",
    "release_date": date(2021, 10, 15),
    "description": None
  }
"""

# Or access attributes directly:
print(movie.title) # The Last Duel
print(movie.release_date) # date(2021, 10, 15)

The IDE can help you understand types and auto-complete attributes:

Type Annotation

Type Annotation


Changelog

0.1.1 (October 2021)

  • Docs improvements
  • Updates setup.py to include stubs package

0.1.0 (October 2021)

  • First release

Testing

Tests are found in a simplified Django project in the /tests folder. Install the project requirements and do ./manage.py test to run them.

License

See License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf-typed-0.1.1.tar.gz (10.7 kB view details)

Uploaded Source

File details

Details for the file drf-typed-0.1.1.tar.gz.

File metadata

  • Download URL: drf-typed-0.1.1.tar.gz
  • Upload date:
  • Size: 10.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.22.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.56.2 CPython/3.8.10

File hashes

Hashes for drf-typed-0.1.1.tar.gz
Algorithm Hash digest
SHA256 703e233165e0c64aa7aa16860a80080ec6e0f40376d2ad07952931ca57cb3a4a
MD5 4e0ae45f9784d56f9a96dec6fe42972e
BLAKE2b-256 2df8cf85e43e6d7e1d2eca8215f029b6364ead21e31c23a7611b7d0733a94c07

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page