11"""
2- NestJS-style decorators for API documentation
2+ Decorators for API documentation
33
44These decorators allow developers to add rich OpenAPI documentation to their routes.
55"""
66
7- from functools import wraps
8- from typing import Type , Dict , Any , List , Optional , Union
7+ from typing import Type , Dict , Any , List
98from .registry import (
109 openapi_registry ,
11- RouteMetadata ,
1210 ResponseMetadata ,
1311 RequestBodyMetadata ,
1412 ParameterMetadata
@@ -22,7 +20,7 @@ def api_operation(
2220 deprecated : bool = False ,
2321):
2422 """
25- Document an API operation (NestJS-style).
23+ Document an API operation
2624
2725 This decorator should be placed closest to the route decorator.
2826
@@ -122,32 +120,44 @@ def api_body(
122120 description : str = "" ,
123121 content_type : str = "application/json" ,
124122 required : bool = True ,
125- examples : Dict [str , Any ] = None
123+ examples : Dict [str , Any ] = None ,
124+ auto_validate : bool = True # NEW: Enable/disable automatic validation
126125):
127126 """
128- Document request body (NestJS -style).
127+ Document request body with AUTOMATIC VALIDATION (FastAPI -style).
129128
130- The DTO class will be used for:
131- 1. OpenAPI schema generation
132- 2. Automatic request validation (via middleware)
129+ By default, this decorator:
130+ 1. Generates OpenAPI schema documentation
131+ 2. Automatically validates incoming requests against the DTO
132+ 3. Provides validated data via req.validated_body
133133
134134 Args:
135135 dto: Request body DTO class (JswebBaseModel subclass)
136136 description: Body description
137137 content_type: MIME type
138138 required: Whether body is required
139139 examples: Example request bodies
140+ auto_validate: Enable automatic validation (default: True)
140141
141142 Example:
142143 @api_bp.route("/users", methods=["POST"])
143144 @api_body(CreateUserDto, description="User data to create")
144145 @api_response(201, UserDto, description="User created")
145146 async def create_user(req):
146- # req.validated_body will contain the validated DTO instance
147- data = await req.json()
148- return json({"user": {...}}, status=201)
147+ # req.validated_body contains the validated DTO instance
148+ # req.validated_data contains the dict representation
149+ user_data = req.validated_data
150+ return json({"user": user_data}, status=201)
151+
152+ # Disable auto-validation if needed:
153+ @api_body(CreateUserDto, auto_validate=False)
154+ async def create_user_manual(req):
155+ data = await req.json() # Manual handling
156+ return json(data)
149157 """
150158 def decorator (handler ):
159+ from .auto_validation import validate_request_body
160+
151161 metadata = openapi_registry .get_or_create_route (handler )
152162
153163 # Get schema from DTO
@@ -168,10 +178,15 @@ def decorator(handler):
168178 dto_class = dto # Store for automatic validation
169179 )
170180
171- # Mark handler with validation info (for middleware)
181+ # Apply automatic validation unless disabled
182+ if auto_validate and not getattr (handler , '_jsweb_disable_validation' , False ):
183+ handler = validate_request_body (dto )(handler )
184+
185+ # Mark handler with validation info
172186 if not hasattr (handler , '_jsweb_validation' ):
173187 handler ._jsweb_validation = {}
174188 handler ._jsweb_validation ['body_dto' ] = dto
189+ handler ._jsweb_validation ['auto_validate' ] = auto_validate
175190
176191 return handler
177192 return decorator
@@ -241,7 +256,7 @@ def api_header(
241256 ** schema_kwargs
242257):
243258 """
244- Document a header parameter (NestJS-style).
259+ Document a header parameter
245260
246261 Args:
247262 name: Header name (e.g., 'Authorization', 'X-API-Key')
@@ -283,7 +298,7 @@ def decorator(handler):
283298
284299def api_security (* schemes : str , scopes : List [str ] = None ):
285300 """
286- Apply security requirements to an operation (NestJS-style).
301+ Apply security requirements to an operation
287302
288303 Args:
289304 *schemes: Security scheme names (must be registered)
@@ -320,7 +335,7 @@ def decorator(handler):
320335
321336def api_tags (* tags : str ):
322337 """
323- Add tags to an operation for grouping in documentation (NestJS-style).
338+ Add tags to an operation for grouping in documentation
324339
325340 Args:
326341 *tags: Tag names
0 commit comments