Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

drf-typed-views

> 后端框架
Open source

Use type annotations to validate/deserialize request parameters in Dango REST Framework.

196 stars0 likes0 views
WebsiteGitHub

About

Use type annotations to validate/deserialize request parameters in Dango REST Framework.

NOT MAINTAINED

Use this project instead: drf-typed.

It includes everything this project does, plus it includes typed features for serializers and helpful type stubs.

Django REST Framework - Typed Views

This project extends Django Rest Framework to allow use of Python's type annotations for automatically validating and casting view parameters. This pattern makes for code that is easier to read and write. View inputs are individually declared, not buried inside all-encompassing request objects. Meanwhile, you get even more out of type annotations: they can replace repetitive validation/sanitization code.

More features:

  • Pydantic models and Marshmallow schemas are compatible types for view parameters. Annotate your POST/PUT functions with them to automatically validate incoming request bodies.
  • Advanced validators for more than just the type: min_value/max_value for numbers
  • Validate string formats: email, uuid and ipv4/6; use Python's native Enum for "choices" validation

Quick example:

python
from rest_typed_views import typed_api_view

@typed_api_view(["GET"])
def get_users(registered_on: date = None, groups: List[int] = None, is_staff: bool = None):
    print(registered_on, groups, is_staff)

GET /users/registered/?registered_on=2019-03-03&groups=4,5&is_staff=yes

Status Code: 200

    date(2019, 3, 3)   [4, 5]  True

GET /users/?registered_on=9999&groups=admin&is_staff=maybe

:no_entry_sign: Status Code: 400 ValidationError raised

json
    {
        "registered_on": "'9999' is not a valid date",
        "groups": "'admin' is not a valid integer",
        "is_staff": "'maybe' is not a valid boolean"
    }

Table of Contents

  • Install & Decorators
  • How It Works: Simple Usage
    • Basic GET Request
    • Basic POST Request
  • How It Works: Advanced Usage
    • Additional Validation Rules
    • Nested Body Fields
    • List Validation
    • Accessing the Request Object
    • Interdependent Query Parameter Validation
    • (Simple) Access Control
  • Enabling Marshmallow, Pydantic Schemas
  • Request Element Classes
    • Query
    • Body
    • Path
    • Header
    • CurrentUser
  • Supported Types/Validator Rules
    • int
    • float
    • Decimal
    • str
    • bool
    • datetime
    • date
    • time
    • timedelta
    • List
    • Enum
    • marshmallow.Schema
    • pydantic.BaseModel
  • Change Log
  • Motivation & Inspiration

Install & Decorators

bash
pip install drf-typed-views

You can add type annotation-enabled features to either ViewSet methods or function-based views using the typed_action and typed_api_view decorators. They take the exact same arguments as Django REST's api_view and action decorators.

How It Works: Simple Usage

For many cases, you can rely on implicit behavior for how different parts of the request (URL path variables, query parameters, body) map to the parameters of a view function/method.

The value of a view parameter will come from...

  • the URL path if the path variable and the view argument have the same name, or:
  • the request body if the view argument is annotated using a class from a supported library for complex object validation (Pydantic, MarshMallow), or:
  • a query parameter with the same name

Unless a default value is given, the parameter is required and a ValidationError will be raised if not set.

Basic GET Request

python
urlpatterns = [
    url(r"^(?P[\w+])/restaurants/", search_restaurants)
]

from rest_typed_views import typed_api_view

# Example request: /chicago/restaurants?delivery=yes
@typed_api_view(["GET"])
def search_restaurants(city: str, rating: float = None, offers_delivery: bool = None):
    restaurants = Restaurant.objects.filter(city=city)

    if rating is not None:
        restaurants = restaurants.filter(rating__gte=rating)

    if offers_delivery is not None:
        restaurants = restaurants.filter(delivery=offers_delivery)

In this example, city is required and must be its string. Its value comes from the URL path variable with the same name. The other parameters, rating and offers_delivery, are not part of the path parameters and are assumed to be query parameters. They both have a default value, so they are optional.

Basic POST Request

…

In this example, city will again be populated using the URL path variable. The booking parameter is annotated using a supported complex schema class (Pydantic), so it's assumed to come from the request body, which will be read in as JSON, used to hydrate the Pydantic BookingSchema and then validated. If validation fails a ValidationError will be raised.

How It Works: Advanced Usage

For more advanced use cases, you can explicitly declare how each parameter's value is sourced from the request -- from the query parameters, path, body or headers -- as well as define additional validation rules. You import a class named after the request element that is expected to hold the value and assign it to the parameter's default.

python
from rest_typed_views import typed_api_view, Query, Path

@typed_api_view(["GET"])
def list_documents(year: date = Path(), title: str = Query(default=None)):
    # ORM logic here...

In this example, year is required and must come from the URL path and title is an optional query parameter because the default is set. This is similar to Django REST's serializer fields: passing a default implies that the filed is not required.

python
from rest_typed_views import typed_api_view, Header

@typed_api_view(["GET"])
def get_cache_header(cache: str = Header()):
    # ORM logic here...

In this example, cache is required and must come from the headers.

Additional Validation Rules

You can use the request element class (Query, Path, Body, Header) to set additional validation constraints. You'll find that these keywords are consistent with Django REST's serializer fields.

python
from rest_typed_views import typed_api_view, Query, Path

@typed_api_view(["GET"])
def search_restaurants(
    year: date = Path(), 
    rating: int = Query(default=None, min_value=1, max_value=5)
):
    # ORM logic here...

@typed_api_view(["GET"])
def get_document(id: str = Path(format="uuid")):
    # ORM logic here...

@typed_api_view(["GET"])
def search_users(
    email: str = Query(default=None, format="email"), 
    ip_address: str = Query(default=None, format="ip"), 
):
    # ORM logic here...

View a full list of supported types and additional validation rules.

Nested Body Fields

Similar to how source is used in Django REST to control field mappings during serialization, you can use it to specify the exact path to the request data.

python
from pydantic import BaseModel
from rest_typed_views import typed_api_view, Query, Path

class Document(BaseModel):
    title: str
    body: str

"""
    POST
    {
        "strict": false,
        "data": {
            "title": "A Dark and Stormy Night",
            "body": "Once upon a time"
        }
    }
"""
@typed_api_view(["POST"])
def create_document(
    strict_mode: bool = Body(source="strict"), 
    item: Document = Body(source="data")
):
    # ORM logic here...

You can also use dot-notation to source data multiple levels deep in the JSON payload.

List Validation

For the basic case of list validation - validating types within a comma-delimited string - declare the type to get automatic validation/coercion:

python
from rest_typed_views import typed_api_view, Query

@typed_api_view(["GET"])
def search_movies(item_ids: List[int] = [])):
    print(item_ids)

# GET /movies?items_ids=41,64,3
# [41, 64, 3]

But you can also specify min_length and max_length, as well as the delimiter and specify additional rules for the child items -- think Django REST's ListField.

Import the generic Param class and use it to set the rules for the child elements:

python
from rest_typed_views import typed_api_view, Query, Param

@typed_api_view(["GET"])
def search_outcomes(
    scores: List[int] = Query(delimiter="|", child=Param(min_value=0, max_value=100))
):
    # ORM logic ...

@typed_api_view(["GET"])
def search_message(
    recipients: List[str] = Query(min_length=1, max_length=10, child=Param(format="email"))
):
    # ORM logic ...

Accessing the Request Object

You probably won't need to access the request object directly, as this package will provide its relevant properties as view arguments. However, you can include it as a parameter annotated with its type and it will be injected:

python
from rest_framework.request import Request
from rest_typed_views import typed_api_view

@typed_api_view(["GET"])
def search_documens(request: Request, q: str = None):
    # ORM logic ...

Interdependent Query Parameter Validation

Often, it's useful to validate a combination of query parameters - for instance, a start_date shouldn't come after an end_date. You can use complex schema object (Pydantic or Marshmallow) for this scenario. In the example below, Query(source="*") is instructing an instance of SearchParamsSchema to be populated/validated using all of the query parameters together: request.query_params.dict().

python
from marshmallow import Schema, fields, validates_schema, ValidationError
from rest_typed_views import typed_api_view

class SearchParamsSchema(Schema):
    start_date = fields.Date()
    end_date = fields.Date()

    @validates_schema
    def validate_numbers(self, data, **kwargs):
        if data["start_date"] >= data["end_date"]:
            raise ValidationError("end_date must come after start_date")

@typed_api_view(["GET"])
def search_documens(search_params: SearchParamsSchema = Query(source="*")):
    # ORM logic ...

(Simple) Access Control

You can apply some very basic access control by applying some validation rules to a view parameter sourced from the CurrentUser request element class. In the example below, a ValidationError will be raised if the request.user is not a member of either super_users or admins.

python
    from my_pydantic_schemas import BookingSchema
    from rest_typed_views import typed_api_view, CurrentUser

    @typed_api_view(["POST"])
    def create_booking(
        booking: BookingSchema, 
        user: User = CurrentUser(member_of_any=["super_users", "admins"])
    ):
        # Do something with the request.user

Read more about the Current User request element class.

Enabling Marshmallow, Pydantic Schemas

As an alternative to Django REST's serializers, you can annotate views with Pydantic models or Marshmallow schemas to have their parameters automat

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythonannotationsdeserializationdjango-rest-frameworktype

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架