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71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index a982b071..c581348c 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -48,7 +48,7 @@ from pydantic.fields import (
     Undefined,
 )
 from pydantic.schema import get_annotation_from_field_info
-from pydantic.typing import evaluate_forwardref
+from pydantic.typing import evaluate_forwardref, get_args, get_origin
 from pydantic.utils import lenient_issubclass
 from starlette.background import BackgroundTasks
 from starlette.concurrency import run_in_threadpool
@@ -56,6 +56,7 @@ from starlette.datastructures import FormData, Headers, QueryParams, UploadFile
 from starlette.requests import HTTPConnection, Request
 from starlette.responses import Response
 from starlette.websockets import WebSocket
+from typing_extensions import Annotated
 
 sequence_shapes = {
     SHAPE_LIST,
@@ -112,18 +113,18 @@ def check_file_field(field: ModelField) -> None:
 
 
 def get_param_sub_dependant(
-    *, param: inspect.Parameter, path: str, security_scopes: Optional[List[str]] = None
+    *,
+    param_name: str,
+    depends: params.Depends,
+    path: str,
+    security_scopes: Optional[List[str]] = None,
 ) -> Dependant:
-    depends: params.Depends = param.default
-    if depends.dependency:
-        dependency = depends.dependency
-    else:
-        dependency = param.annotation
+    assert depends.dependency
     return get_sub_dependant(
         depends=depends,
-        dependency=dependency,
+        dependency=depends.dependency,
         path=path,
-        name=param.name,
+        name=param_name,
         security_scopes=security_scopes,
     )
 
@@ -298,122 +299,199 @@ def get_dependant(
         use_cache=use_cache,
     )
     for param_name, param in signature_params.items():
-        if isinstance(param.default, params.Depends):
+        is_path_param = param_name in path_param_names
+        type_annotation, depends, param_field = analyze_param(
+            param_name=param_name,
+            annotation=param.annotation,
+            value=param.default,
+            is_path_param=is_path_param,
+        )
+        if depends is not None:
             sub_dependant = get_param_sub_dependant(
-                param=param, path=path, security_scopes=security_scopes
+                param_name=param_name,
+                depends=depends,
+                path=path,
+                security_scopes=security_scopes,
             )
             dependant.dependencies.append(sub_dependant)
             continue
-        if add_non_field_param_to_dependency(param=param, dependant=dependant):
+        if add_non_field_param_to_dependency(
+            param_name=param_name,
+            type_annotation=type_annotation,
+            dependant=dependant,
+        ):
+            assert (
+                param_field is None
+            ), f"Cannot specify multiple FastAPI annotations for {param_name!r}"
             continue
-        param_field = get_param_field(
-            param=param, default_field_info=params.Query, param_name=param_name
-        )
-        if param_name in path_param_names:
-            assert is_scalar_field(
-                field=param_field
-            ), "Path params must be of one of the supported types"
-            ignore_default = not isinstance(param.default, params.Path)
-            param_field = get_param_field(
-                param=param,
-                param_name=param_name,
-                default_field_info=params.Path,
-                force_type=params.ParamTypes.path,
-                ignore_default=ignore_default,
-            )
-            add_param_to_fields(field=param_field, dependant=dependant)
-        elif is_scalar_field(field=param_field):
-            add_param_to_fields(field=param_field, dependant=dependant)
-        elif isinstance(
-            param.default, (params.Query, params.Header)
-        ) and is_scalar_sequence_field(param_field):
-            add_param_to_fields(field=param_field, dependant=dependant)
-        else:
-            field_info = param_field.field_info
-            assert isinstance(
-                field_info, params.Body
-            ), f"Param: {param_field.name} can only be a request body, using Body()"
+        assert param_field is not None
+        if is_body_param(param_field=param_field, is_path_param=is_path_param):
             dependant.body_params.append(param_field)
+        else:
+            add_param_to_fields(field=param_field, dependant=dependant)
     return dependant
 
 
 def add_non_field_param_to_dependency(
-    *, param: inspect.Parameter, dependant: Dependant
+    *, param_name: str, type_annotation: Any, dependant: Dependant
 ) -> Optional[bool]:
-    if lenient_issubclass(param.annotation, Request):
-        dependant.request_param_name = param.name
+    if lenient_issubclass(type_annotation, Request):
+        dependant.request_param_name = param_name
         return True
-    elif lenient_issubclass(param.annotation, WebSocket):
-        dependant.websocket_param_name = param.name
+    elif lenient_issubclass(type_annotation, WebSocket):
+        dependant.websocket_param_name = param_name
         return True
-    elif lenient_issubclass(param.annotation, HTTPConnection):
-        dependant.http_connection_param_name = param.name
+    elif lenient_issubclass(type_annotation, HTTPConnection):
+        dependant.http_connection_param_name = param_name
         return True
-    elif lenient_issubclass(param.annotation, Response):
-        dependant.response_param_name = param.name
+    elif lenient_issubclass(type_annotation, Response):
+        dependant.response_param_name = param_name
         return True
-    elif lenient_issubclass(param.annotation, BackgroundTasks):
-        dependant.background_tasks_param_name = param.name
+    elif lenient_issubclass(type_annotation, BackgroundTasks):
+        dependant.background_tasks_param_name = param_name
         return True
-    elif lenient_issubclass(param.annotation, SecurityScopes):
-        dependant.security_scopes_param_name = param.name
+    elif lenient_issubclass(type_annotation, SecurityScopes):
+        dependant.security_scopes_param_name = param_name
         return True
     return None
 
 
-def get_param_field(
+def analyze_param(
     *,
-    param: inspect.Parameter,
     param_name: str,
-    default_field_info: Type[params.Param] = params.Param,
-    force_type: Optional[params.ParamTypes] = None,
-    ignore_default: bool = False,
-) -> ModelField:
-    default_value: Any = Undefined
-    had_schema = False
-    if not param.default == param.empty and ignore_default is False:
-        default_value = param.default
-    if isinstance(default_value, FieldInfo):
-        had_schema = True
-        field_info = default_value
-        default_value = field_info.default
-        if (
+    annotation: Any,
+    value: Any,
+    is_path_param: bool,
+) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]:
+    field_info = None
+    used_default_field_info = False
+    depends = None
+    type_annotation: Any = Any
+    if (
+        annotation is not inspect.Signature.empty
+        and get_origin(annotation) is Annotated  # type: ignore[comparison-overlap]
+    ):
+        annotated_args = get_args(annotation)
+        type_annotation = annotated_args[0]
+        fastapi_annotations = [
+            arg
+            for arg in annotated_args[1:]
+            if isinstance(arg, (FieldInfo, params.Depends))
+        ]
+        assert (
+            len(fastapi_annotations) <= 1
+        ), f"Cannot specify multiple `Annotated` FastAPI arguments for {param_name!r}"
+        fastapi_annotation = next(iter(fastapi_annotations), None)
+        if isinstance(fastapi_annotation, FieldInfo):
+            field_info = fastapi_annotation
+            assert field_info.default is Undefined or field_info.default is Required, (
+                f"`{field_info.__class__.__name__}` default value cannot be set in"
+                f" `Annotated` for {param_name!r}. Set the default value with `=` instead."
+            )
+            if value is not inspect.Signature.empty:
+                assert not is_path_param, "Path parameters cannot have default values"
+                field_info.default = value
+            else:
+                field_info.default = Required
+        elif isinstance(fastapi_annotation, params.Depends):
+            depends = fastapi_annotation
+    elif annotation is not inspect.Signature.empty:
+        type_annotation = annotation
+
+    if isinstance(value, params.Depends):
+        assert depends is None, (
+            "Cannot specify `Depends` in `Annotated` and default value"
+            f" together for {param_name!r}"
+        )
+        assert field_info is None, (
+            "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a"
+            f" default value together for {param_name!r}"
+        )
+        depends = value
+    elif isinstance(value, FieldInfo):
+        assert field_info is None, (
+            "Cannot specify FastAPI annotations in `Annotated` and default value"
+            f" together for {param_name!r}"
+        )
+        field_info = value
+
+    if depends is not None and depends.dependency is None:
+        depends.dependency = type_annotation
+
+    if lenient_issubclass(
+        type_annotation,
+        (Request, WebSocket, HTTPConnection, Response, BackgroundTasks, SecurityScopes),
+    ):
+        assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}"
+        assert (
+            field_info is None
+        ), f"Cannot specify FastAPI annotation for type {type_annotation!r}"
+    elif field_info is None and depends is None:
+        default_value = value if value is not inspect.Signature.empty else Required
+        if is_path_param:
+            # We might check here that `default_value is Required`, but the fact is that the same
+            # parameter might sometimes be a path parameter and sometimes not. See
+            # `tests/test_infer_param_optionality.py` for an example.
+            field_info = params.Path()
+        else:
+            field_info = params.Query(default=default_value)
+        used_default_field_info = True
+
+    field = None
+    if field_info is not None:
+        if is_path_param:
+            assert isinstance(field_info, params.Path), (
+                f"Cannot use `{field_info.__class__.__name__}` for path param"
+                f" {param_name!r}"
+            )
+        elif (
             isinstance(field_info, params.Param)
             and getattr(field_info, "in_", None) is None
         ):
-            field_info.in_ = default_field_info.in_
-        if force_type:
-            field_info.in_ = force_type  # type: ignore
-    else:
-        field_info = default_field_info(default=default_value)
-    required = True
-    if default_value is Required or ignore_default:
-        required = True
-        default_value = None
-    elif default_value is not Undefined:
-        required = False
-    annotation: Any = Any
-    if not param.annotation == param.empty:
-        annotation = param.annotation
-    annotation = get_annotation_from_field_info(annotation, field_info, param_name)
-    if not field_info.alias and getattr(field_info, "convert_underscores", None):
-        alias = param.name.replace("_", "-")
-    else:
-        alias = field_info.alias or param.name
-    field = create_response_field(
-        name=param.name,
-        type_=annotation,
-        default=default_value,
-        alias=alias,
-        required=required,
-        field_info=field_info,
-    )
-    if not had_schema and not is_scalar_field(field=field):
-        field.field_info = params.Body(field_info.default)
-    if not had_schema and lenient_issubclass(field.type_, UploadFile):
-        field.field_info = params.File(field_info.default)
+            field_info.in_ = params.ParamTypes.query
+        annotation = get_annotation_from_field_info(
+            annotation if annotation is not inspect.Signature.empty else Any,
+            field_info,
+            param_name,
+        )
+        if not field_info.alias and getattr(field_info, "convert_underscores", None):
+            alias = param_name.replace("_", "-")
+        else:
+            alias = field_info.alias or param_name
+        field = create_response_field(
+            name=param_name,
+            type_=annotation,
+            default=field_info.default,
+            alias=alias,
+            required=field_info.default in (Required, Undefined),
+            field_info=field_info,
+        )
+        if used_default_field_info:
+            if lenient_issubclass(field.type_, UploadFile):
+                field.field_info = params.File(field_info.default)
+            elif not is_scalar_field(field=field):
+                field.field_info = params.Body(field_info.default)
+
+    return type_annotation, depends, field
+
 
-    return field
+def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool:
+    if is_path_param:
+        assert is_scalar_field(
+            field=param_field
+        ), "Path params must be of one of the supported types"
+        return False
+    elif is_scalar_field(field=param_field):
+        return False
+    elif isinstance(
+        param_field.field_info, (params.Query, params.Header)
+    ) and is_scalar_sequence_field(param_field):
+        return False
+    else:
+        assert isinstance(
+            param_field.field_info, params.Body
+        ), f"Param: {param_field.name} can only be a request body, using Body()"
+        return True
 
 
 def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:
diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py
index 1932ef06..75f054e9 100644
--- a/fastapi/param_functions.py
+++ b/fastapi/param_functions.py
@@ -5,7 +5,7 @@ from pydantic.fields import Undefined
 
 
 def Path(  # noqa: N802
-    default: Any = Undefined,
+    default: Any = ...,
     *,
     alias: Optional[str] = None,
     title: Optional[str] = None,
diff --git a/fastapi/params.py b/fastapi/params.py
index 5395b98a..16c5c309 100644
--- a/fastapi/params.py
+++ b/fastapi/params.py
@@ -62,7 +62,7 @@ class Path(Param):
 
     def __init__(
         self,
-        default: Any = Undefined,
+        default: Any = ...,
         *,
         alias: Optional[str] = None,
         title: Optional[str] = None,
@@ -80,9 +80,10 @@ class Path(Param):
         include_in_schema: bool = True,
         **extra: Any,
     ):
+        assert default is ..., "Path parameters cannot have a default value"
         self.in_ = self.in_
         super().__init__(
-            default=...,
+            default=default,
             alias=alias,
             title=title,
             description=description,
@@ -279,7 +280,7 @@ class Body(FieldInfo):
 class Form(Body):
     def __init__(
         self,
-        default: Any,
+        default: Any = Undefined,
         *,
         media_type: str = "application/x-www-form-urlencoded",
         alias: Optional[str] = None,
@@ -319,7 +320,7 @@ class Form(Body):
 class File(Form):
     def __init__(
         self,
-        default: Any,
+        default: Any = Undefined,
         *,
         media_type: str = "multipart/form-data",
         alias: Optional[str] = None,
diff --git a/fastapi/utils.py b/fastapi/utils.py
index 391c47d8..d8be53c5 100644
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -1,4 +1,3 @@
-import functools
 import re
 import warnings
 from dataclasses import is_dataclass
@@ -73,19 +72,17 @@ def create_response_field(
     class_validators = class_validators or {}
     field_info = field_info or FieldInfo()
 
-    response_field = functools.partial(
-        ModelField,
-        name=name,
-        type_=type_,
-        class_validators=class_validators,
-        default=default,
-        required=required,
-        model_config=model_config,
-        alias=alias,
-    )
-
     try:
-        return response_field(field_info=field_info)
+        return ModelField(
+            name=name,
+            type_=type_,
+            class_validators=class_validators,
+            default=default,
+            required=required,
+            model_config=model_config,
+            alias=alias,
+            field_info=field_info,
+        )
     except RuntimeError:
         raise fastapi.exceptions.FastAPIError(
             "Invalid args for response field! Hint: "