rsinger86 / drf-typed

Type hints for enhanced API views and serializers.
https://rsinger86.github.io/drf-typed/
MIT License
79 stars 5 forks source link
django django-rest-framework serializer type-annotations type-hints validation

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:

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


Install

Install using:

pip install drf-typed

Python 3.8 or higher is required.

Changelog

0.3.0 (March 2023)

0.2.0 (January 2022)

0.1.3 (October 2021)

0.1.1 (October 2021)

0.1.0 (October 2021)

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.