# Issue #12780: Dependency Injection and Field Validation
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

code
```
def get_db():
    db = SessionLocal2()
    try:
        yield db
    except Exception as e:
        logger.exception(e)
        db.rollback()
        raise e
    finally:
        db.close()
class NurseNewSchema(BaseModel):
    family_user_id: str
    time_day: int
    nurse_master: str
    nurse_remarks: str | None
    nurse_title: str

async def post_new_nurse(item: NurseNewSchema, db=Depends(get_db)):
    pass
```
When nurse_master is not filled in, data verification fails, but the interface executes to get_db, and when yielding db, it reports data verification failure.

2024-11-06 09:58:29.965 | ERROR    | core:get_db:59 - [{'loc': ('body', 'nurse_master'), 'msg': 'field required', 'type': 'value_error.missing'}]
Traceback (most recent call last):

  File "/usr/lib/python3.10/threading.py", line 973, in _bootstrap
    self._bootstrap_inner()
    │    └ <function Thread._bootstrap_inner at 0x7fd6edf39090>
    └ <WorkerThread(AnyIO worker thread, started 140559949760064)>
  File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
    │    └ <function WorkerThread.run at 0x7fd6c1500430>
    └ <WorkerThread(AnyIO worker thread, started 140559949760064)>
  File "/home/ouyang/.env/paper/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 807, in run
    result = context.run(func, *args)
             │       │   │      └ (<class 'fastapi.exceptions.RequestValidationError'>, RequestValidationError([{'loc': ('body', 'nurse_master'), 'msg': 'field...
             │       │   └ <bound method _GeneratorContextManager.__exit__ of <contextlib._GeneratorContextManager object at 0x7fd6c154d930>>
             │       └ <method 'run' of '_contextvars.Context' objects>
             └ <_contextvars.Context object at 0x7fd6d9e22700>
  File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
    self.gen.throw(typ, value, traceback)
    │    │   │     │    │      └ None
    │    │   │     │    └ RequestValidationError([{'loc': ('body', 'nurse_master'), 'msg': 'field required', 'type': 'value_error.missing'}])
    │    │   │     └ <class 'fastapi.exceptions.RequestValidationError'>
    │    │   └ <method 'throw' of 'generator' objects>
    │    └ <generator object get_db at 0x7fd6c1537b50>
    └ <contextlib._GeneratorContextManager object at 0x7fd6c154d930>

> File "/home/ouyang/Desktop/poc/core.py", line 55, in get_db
    yield db
          └ <sqlalchemy.orm.session.Session object at 0x7fd6c154de10>
fastapi.exceptions.RequestValidationError: [{'loc': ('body', 'nurse_master'), 'msg': 'field required', 'type': 'value_error.missing'}]

---
Comment: The error is happening because FastAPI is trying to yield the db session in get_db() before it handles the validation error. By ensuring that the validation happens before calling the dependency (get_db), the session will only be created if the input is valid. This prevents unnecessary database connections in case of invalid input.

1)Refactor get_db() as a Context Manager: This keeps the session logic clear and prevents unnecessary session creation before validation.
2)Ensure Validation Happens First: FastAPI will validate item (which is the body input) before get_db is even called. So if there’s any validation failure, it will happen before the DB session is created.
3)Error Handling in get_db(): If an exception is raised (such as a validation error), get_db() will log and handle it without impacting the database session.
---
Comment: > This prevents unnecessary database connections in case of invalid input.

In production applications it is common to create SQLAlchemy's Engine, and then use it so create sessions. Engine is a connection pool, so it doesn't really create new session each time, but reuses already opened session from the pool.


# Issue #12901: Upcoming Pydantic 2.10 is going to break version comparison checks
Labels: bug
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

The following check:

https://github.com/fastapi/fastapi/blob/5a48c37056397e47ab164ba4430807aa6fc9a710/fastapi/params.py#L108-L109

is going to be flawed when we release Pydantic 2.10 (in a week):

```python
"2.10.0" > "2.7.0"
#> False
```
---
Comment: Thanks for the report @Viicos! I handled it in https://github.com/fastapi/fastapi/pull/12914, it will be released in the next hours. :nerd_face:


# Issue #12924: Do you have a performance checker for FaskAPI? The problem is that when you make 100 concurrent requests, the API returns are slow. How do you solve it?
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

![image](https://github.com/user-attachments/assets/531ebf3c-0d76-4241-a742-b9286e20736d)
![image](https://github.com/user-attachments/assets/7942db47-2a25-4af7-aaa1-4a6c40ccd735)
![image](https://github.com/user-attachments/assets/c91ae68c-e57c-471b-a182-b0a49dea3df6)
Is there a problem with the code, is there any code to refer to, or is there a health monitoring tool to check the FaskAPI


# Issue #12936: Starting multiple processes within multiple processes in Python
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

I defined a multiprocessing pool in the initialization function, and then started multiple processes within a single process, resulting in an error.：：AssertionError: daemonic processes are not allowed to have children
The code works fine outside of your framework, so is it due to some limitations in your framework or another reason?


# Issue #12963: Fastapi performance issue not responding  important
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

Hai
We using fastapi last 1.5 Yr we facing daily issues on that on performance like 100 to 200 clients requesting every 5 sec some time not responding some time totally hanging we restarting the services
Additional information we used mysql


# Issue #12965: Will FastAPI support QUERY http method? "app.query"
Labels: feature
### Discussed in https://github.com/fastapi/fastapi/discussions/6049

Originally posted by **FilipeMarch** December 16, 2022
### First Check

- [X] I added a very descriptive title to this issue.
- [X] I used the GitHub search to find a similar issue and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from fastapi import FastAPI

app = FastAPI()

@app.query('/query/subjects')
def query_subjects(schema: ArbitrarySchema):
    with Session(engine) as db:
        subjects = db.query(Subject).all()
        return schema(**subjects)

# something like this
```

### Description

There is a new HTTP method called QUERY, I discovered it this week and it is super interesting!

https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html

I was trying to make a GET route that would accept a request body, but started receiving an error on Swagger UI:

[TypeError: Request has method 'GET' and cannot have a body](https://github.com/swagger-api/swagger-ui/issues/5891#issuecomment-1340591857)

The idea is that sometimes we need to make a big or complex query, and this is the scenario in which we can see the advantages of GraphQL, and although I have seen that [we can integrate FastAPI with GraphQL](https://fastapi.tiangolo.com/advanced/graphql/), I was wondering if FastAPI will ever be able to simply accept a QUERY method like, for example, `app.query("/query/subjects")`.

For example, suppose I have this object:
```yml
{
   "id": 1,
   "name": "Math"
   "tags": [
       {
           "id": 1,
           "name": "Algebra",
           "number_of_clicks": 1,
           "number_of_questions": 7,
           "number_of_answers": 3,
           "number_of_comments": 2,
           "number_of_votes": 1,
       }]
   "topics": [
       {
           "id": 1,
           "name": "Linear Equations",
           "likes": 1,
           "dislikes": 0,
           "number_of_clicks": 1,
           "number_of_tutorials": 1,
           "number_of_questions": 7,
           "posts": [
               {
                   "id": 1,
                   "title": "How to solve linear equations?",
                   "likes": 1,
                   "dislikes": 0,
                   "number_of_clicks": 1,
---
Comment: We should wait OpenAPI to support it.
---
Comment: I think https://github.com/OAI/OpenAPI-Specification/issues/1747 needs to happen before this issue.
---
Comment: Forgive me if this is premature, but it looks like the [v3.2-dev branch](https://github.com/OAI/OpenAPI-Specification/tree/v3.2-dev) has the feature this was waiting on in it. [The fix was merged back in April](https://github.com/OAI/OpenAPI-Specification/pull/4514).


# Issue #12987: FastApi website issue
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

Issue in Fastapi website in ubuntu-mint flavor

Look at the top of the menu bar

![image](https://github.com/user-attachments/assets/ffe82cdf-2e9f-4d49-bef8-6ceea8c57e85)


# Issue #13019: Multipart upload is not working without a trailing slash
```
Expected boundary character 45, got 20 at index 2
```

Related:
https://github.com/fastapi/fastapi/discussions/7062#discussioncomment-6090647_
---
Comment: How can I reproduce?
---
Comment: ```py
@app.post("/search/")
async def search(file: UploadFile = File(...)):
    image = Image.open(io.BytesIO(await file.read()))
```
---
Comment: Please create a discussion with a code that can be easily reproducible - including imports, and how to call this code.


# Issue #13022: Traceback stack does not show exact place of error
Labels: question, question-migrate
### Discussed in https://github.com/fastapi/fastapi/discussions/8428

Originally posted by **NewSouthMjos** December  5, 2022
### First Check

- [X] I added a very descriptive title to this issue.
- [X] I used the GitHub search to find a similar issue and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [x] I commit to help with one of those options 👆

### Example Code

```python
import uvicorn
from fastapi import FastAPI, Depends

app = FastAPI()

def get_something_sync():
    yield True

async def get_something_async():
    yield True

@app.get('/1')
def router_func(dependency=Depends(get_something_sync)):
    raise ValueError
    return

@app.get('/2')
def router_func(dependency=Depends(get_something_async)):
    raise ValueError
    return

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=5600, workers=1)
```

### Description

If dependency function uses yield, injecting dependency with sync def function (get_something_sync), the error traceback will broke - it doesn't locate the place where it was rise (should be "/app/main.py", line 24)
calling endpoint /1:
```
fastapi_dependency  | INFO:     10.77.78.83:60070 - "GET /1 HTTP/1.1" 500 Internal Server Error
fastapi_dependency  | ERROR:    Exception in ASGI application
fastapi_dependency  | Traceback (most recent call last):
fastapi_dependency  |   File "/usr/local/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 419, in run_asgi
fastapi_dependency  |     result = await app(  # type: ignore[func-returns-value]
fastapi_dependency  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
fastapi_dependency  |   File "/usr/local/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
fastapi_dependency  |     return await self.app(scope, receive, send)
fastapi_dependency  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
fastapi_dependency  |   File "/usr/local/lib/python3.11/site-packages/fastapi/applications.py", line 270, in __call__
fastapi_dependency  |     await super().__call__(scope, receive, send)
fastapi_dependency  |   File "/usr/local/lib/python3.11/site-packages/starlette/applications.py", line 124, in __call__
fastapi_dependency  |     await self.middleware_stack(scope, receive, send)
fastapi_dep
---
Comment: I've simplified a bit the PR that solves this: https://github.com/fastapi/fastapi/pull/5823
---
Comment: I think the issue is not what it's described here, but I'll not spam another one to not create confusion.

The issue is actually this one: https://github.com/fastapi/fastapi/discussions/12999

The one mentioned in this issue is very similar, but it was solved.


# Issue #13023: StreamingResponse was block my program???
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

async def generate_predictions(model_name):
    global stop_flag
    mean, std, labels, model, pca_model = get_init(model_name)
    async for prediction in collect_predict(mean, std, labels, model, pca_model):
        if stop_flag == True:
            stop_flag = False
            break
        yield json.dumps({"prediction": prediction}) + "\n"

@router.get("/end_predict")
def end_predict():
    global stop_flag
    stop_flag = True
    return {'message' : 'End predict'}

@router.post("/predict")
def predict_func(data: predict):
    model_name = data.name_predict
    return StreamingResponse(
        generate_predictions(model_name),
        media_type="application/json"
    )


# Issue #13056: Can't use `Annotated` with `ForwardRef`
Labels: bug
### Issue Content

The following code doesn't generate the correct OpenAPI json:

```py
from __future__ import annotations

from dataclasses import dataclass
from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()

def get_potato() -> Potato:
    return Potato(color='red', size=10)

@app.get('/')
async def read_root(potato: Annotated[Potato, Depends(get_potato)]):
    return {'Hello': 'World'}

@dataclass
class Potato:
    color: str
    size: int
```

If we move the `Potato` up, or remove the `Annotated`, then it works as expected.
---
Comment: > [...] I think you'll get the same error if Potato was defined earlier.

No, the problem here is `Potato` after.

> What does the generated json look like? Do we get 'Annotated[Potato, Depends(get_potato)]' rather than the actual type?

The `potato` is a query parameter on the generated OpenAPI. But you can run it, and check by yourself... 👀
---
Comment: I ran into this issue with caused debugging hell, there's a function already part of the standard library that solves most of the complicated logic: https://typing-extensions.readthedocs.io/en/latest/index.html#typing_extensions.get_annotations.
---
Comment: I've explored the codebase, and although it seems #14557 and #14703 were associated with this issue to attempt to fix. I have some ideas on making the check a bit more robust so we can cover variations such as `typing.Annotated` or even type aliasing.

If there is interest, I can take a stab and open a PR in the next day or so?


# Issue #13067: poor quality traceback / useful stack frames not present when exceptions raised in sync dependencies
### Privileged issue

- [X] I'm ~@tiangolo or he asked me directly to create an issue here~ a liar, but the discussion template was crazy onerous, and I'm confident I can write a decent, succinct issue description that's worth reading here ;-)

### Issue Content

If I apply this diff to the [full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template/blob/88c83cc06ccab67efa839c2c0994435b727986a3/backend/app/api/deps.py#L21-L23):

```diff
diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py
index c2b83c8..c99cdb2 100644
--- a/backend/app/api/deps.py
+++ b/backend/app/api/deps.py
@@ -19,6 +19,7 @@ reusable_oauth2 = OAuth2PasswordBearer(

 def get_db() -> Generator[Session, None, None]:
+    raise Exception("error")
     with Session(engine) as session:
         yield session
```

...and issue a GET to `http://127.0.0.1:8000/api/v1/users/`, the traceback shown in the console is really unhelpful:

```
  File "...3.11/lib/python3.11/contextlib.py", line 650, in enter_async_context
    result = await _enter(cm)
             ^^^^^^^^^^^^^^^^
  File "...3.11/lib/python3.11/contextlib.py", line 210, in __aenter__
    return await anext(self.gen)
           ^^^^^^^^^^^^^^^^^^^^^
  File ".../full-stack-fastapi-template/backend/.venv/lib/python3.11/site-packages/fastapi/concurrency.py", line 35, in contextmanager_in_threadpool
    raise e
Exception: error

```

There are no frames from the actual site of the exception, and, on the face of it, potentially no way to go back from the exception to the source of the error.

I first noticed this doing test driven development on a new FastAPI project, having not done any FastAPI dev for a couple of years, and was pretty shocked.

What I don't understand is why the exception being re-raised appears to have no traceback of its own?
---
Comment: Did you try the last FastAPI version?
---
Comment: Close enough:

```
$ uv tree | grep -i fast
Resolved 81 packages in 0.92ms
├── fastapi[standard] v0.115.0
│   ├── fastapi-cli[standard] v0.0.5 (extra: standard)
├── sentry-sdk[fastapi] v1.45.1
│   └── fastapi v0.115.0 (extra: fastapi) (*)
```

Dropped a breakpoint, does indeed appear that `__traceback__` is None, but why?

```
> .../python3.11/site-packages/fastapi/concurrency.py(36)contextmanager_in_threadpool()
-> raise e
(Pdb) !e
Exception('error')
(Pdb) !e.__traceback__
(Pdb) !e.__traceback__ is None
True
```
---
Comment: Can you try on the really latest?


# Issue #13111: Incorrect handling of non utf-8 data in body in case of a validataion error
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

There was no way to report actual issue by the rules so I had to lie about being able to do so...
There has to be a section in discussions or something then.

```
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "REDACTED\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
    await app(scope, receive, sender)
  File "REDACTED\.venv\Lib\site-packages\starlette\routing.py", line 72, in app
    response = await func(request)
               ^^^^^^^^^^^^^^^^^^^
  File "REDACTED\.venv\Lib\site-packages\fastapi\routing.py", line 315, in app
    raise validation_error
fastapi.exceptions.RequestValidationError: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': b'----cpp-httplib-multipart-data-UxL5MB5nIRg5wqYk\r\nContent-Disposition: form-data; name="metadata"\r\nContent-Type: application/json\r\n\r\n{"started":1735320698,"length_seconds":3}\r\n----cpp-httplib-multipart-data-UxL5MB5nIRg5wqYk\r\nContent-Disposition: form-data; name="metadata"; filename="main.ogg"\r\nContent-Type: audio/ogg\r\n\r\nOggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x81Z\x97E\x00\x00\x00\x00\x0b\xffmn\x01\x13OpusHead\x01\x028\x01\x80>\x00\x00\x00\x00\x00OggS\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x81Z\x97E\x01\x00\x00\x00\xf3sR\x98\x01\'OpusTags\x17\x00\x00\x00recorder ogg-opus 0.0.1\x00\x00\x00\x00OggS\x00\x00\xc0\xf3\x00\x00\x00\x00\x00\x00\x81Z\x97E\x02\x00\x00\x00\xd2\xf2\x8d<A\x14\x1b\r\n----cpp-httplib-multipart-data-UxL5MB5nIRg5wqYk--\r\n'}]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "REDACTED\.venv\Lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 419, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "REDACTED\.venv\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 84, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "REDACTED\.venv\Lib\site-packages\fastapi\applications.py", line 1054, in __call__
    await super().__call__(scope, receive, send)
  File "REDACTED\.venv\Lib\site-packages\starlette\applications.py", line 123, in __call__
    await self.middleware_stack(scope, receive, send)
  File "REDACTED\.venv\Lib\site-packages\starlette\middleware\errors.py", line 186, in __call__
    raise exc
  File "REDACTED\.venv\Lib\site-packages\starlette\middleware\errors.py", line 164, in __call__
    await self.app(scope, receive, _send)
  File "REDACTED\.venv\Lib\site-packages\starlette\middleware\cors.py", line 85, in __call__
    await self.app(scope, receive, send)
  File "REDACTED\.venv\Lib\site-packages\starlette\middleware\exc
---
Comment: Well, the issue is too vague. You should at least share what string is causing the issue.


# Issue #13116: background tasks don't run when raise a HTTPException
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

```python
from fastapi import FastAPI, HTTPException, BackgroundTasks

app = FastAPI()

items = {
    'apple': 10,
    'banana': 5,
}

def task1():
    print("Task 1 is running in the background")

@app.get("/items/{name}")
async def read_item(name: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(task1)

    if name in items:
        return {"name": name, "count": items[name]}
    else:
        raise HTTPException(status_code=404, detail="Item not found")
```

1. when ```name is``` found in ```items```, background is excuted :

```
curl -X 'GET' \
  'http://127.0.0.1:8006/items/apple' \
  -H 'accept: application/json'
```
console output
```
INFO:     127.0.0.1:58360 - "GET /items/apple HTTP/1.1" 200 OK
Task 1 is running in the background
```

2.  when ```name``` is found in ```items```, background is ***not*** excuted :

```
curl -X 'GET' \
  'http://127.0.0.1:8006/items/orange' \
  -H 'accept: application/json'
```
console output
```
INFO:     127.0.0.1:58360 - - "GET /items/orange HTTP/1.1" 404 Not Found
```
---
Comment: if I want to record something when raise a HTTPException in background task, what should I can do?
---
Comment: This is not a bug.

It's the intended behavior. Background tasks only run if 2xx is sent back.


# Issue #13119: When I use contextvars, I unexpectedly found that FastAPI clears the content I set somewhere. Is this result normal?
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

#### code
```
def print_task_id(mn: str):
    try:
        print(mn, "task_id", id(asyncio.current_task()))
    except Exception:
        print(mn, "task_id", "None")

def print_thread_id(flag: str):
    print(flag, "thread id:", threading.current_thread().ident)

def print_contextvars_name(flag: str):
    print(flag, "contextvars_name:", contextvars_name.get())

def print_all(flag: str):
    print_thread_id(flag)
    print_task_id(flag)
    print_contextvars_name(flag)

@router.get("/test1")
def test(cn: str | None = None):
    print_all("test1")
    if cn:
        contextvars_name.set(cn)
        print_all("test1")
    return R("test1")
```
#### steps
access to test1,param.cn=tt1
access to test1
#### log
```
INFO:     Uvicorn running on http://0.0.0.0:8091 (Press CTRL+C to quit)
INFO:     127.0.0.1:60430 - "GET /docs_local HTTP/1.1" 200 OK
INFO:     127.0.0.1:60430 - "GET /static/swagger-ui/swagger-ui.css HTTP/1.1" 200 OK
INFO:     127.0.0.1:60431 - "GET /static/swagger-ui/swagger-ui-bundle.js HTTP/1.1" 200 OK
INFO:     127.0.0.1:60431 - "GET /openapi.json HTTP/1.1" 200 OK
test1 thread id: 24496
test1 task_id None
test1 contextvars_name: contextvars_name_default
test1 thread id: 24496
test1 task_id None
test1 contextvars_name: tt1
INFO:     127.0.0.1:60432 - "GET /test/test1?cn=tt1 HTTP/1.1" 200 OK
test1 thread id: 24496
test1 task_id None
test1 contextvars_name: contextvars_name_default
test1 thread id: 24496
test1 task_id None
test1 contextvars_name: tt1
INFO:     127.0.0.1:60432 - "GET /test/test1?cn=tt1 HTTP/1.1" 200 OK
```
#### question
With the same thread_id, I did not clear contextvars_name, but when I made the second request, the value of contextvars_name was not the one I set during the first request.
#### version
fastapi==0.115.6


# Issue #13150: Simplify tests for variants
### Privileged issue

- [X] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

## Summary

Simplify tests for variants, from multiple test files (one test file per variant) to a single test file with parameters to test each variant.

## Background

Currently, we have multiple source example variants for different Python versions:

* Python 3.8
* Python 3.9
* Python 3.10

And we have versions using `Annotated` and without using it.

Combining that, for each source app, we end up with different variants.

For example, for `docs_src/query_params_str_validations/tutorial010.py`, for this same `tutorial010`, we have these variants:

* `docs_src/query_params_str_validations/tutorial010_an_py39.py`
    * Using `Annotated`, Python 3.9.
* `docs_src/query_params_str_validations/tutorial010_an_py310.py`
    * Using `Annotated`, Python 3.10.
* `docs_src/query_params_str_validations/tutorial010_an.py`
    * Using `Annotated`, Python 3.8 (as 3.8 is the oldest, this one doesn't have a part in the name like `py38`).
* `docs_src/query_params_str_validations/tutorial010_py310.py`
    * Python 3.10, not using `Annotated` (as not using `Annotated` is the oldest form, it just doesn't have the `an` part in the file name.
* `docs_src/query_params_str_validations/tutorial010.py`
    * Not using `Annotated`, Python 3.8.

Each of these files represent the same FastAPI app, but with the improved syntax for Python 3.9, or 3.10, or using `Annotated`, but in the end, the same app.

We want to keep these files like this because they have the different ways to create an app, the different supported syntaxes, including backward-compatible ones. They are shown in the docs and tested on CI.

Then, we have tests for that... currently, we just have a test file per variant file, so, we have:

* `tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py`
* `tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py`
* `tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py`
* `tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py`
* `tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py`

But then, each of the files is almost exactly the same code, only with Pytest "markers" to define that something should only be run on Python 3.10, etc. but apart from that, they have the same code.

## The Task

The task is to replace the multiple **test** files for each variant with a single file that uses Pytest parameters to import each specific app, and that uses Pytest markers for the files that require a specific version of Python.

An example of the result for one of these test variants is here: https://github.com/fastapi/fastapi/pull/13149

Not all tutorial tests have multiple variants, but there are a few that do. This can be done in one PR per tutorial (with the single test for all its varian
---
Comment: @alejsdev: I think I will be able to help. Please let me know which tests I can do.

~~`tests.test_tutorial.tests_query_params`: #13215~~
`test_query_params_str_validations`: #13218
`test_testing`: #13220:  I'm not sure about that one, and it might be wrong.
`test_testing_dependencies`:  #13223 I'm not sure about that one, and it might be wrong.
---
Comment: I can help , please let me know the tests to be worked on.
---
Comment: Hi @alejsdev @tiangolo. May you please take a look at my open PRs above?
Thank you :)


# Issue #13175: Duplicated OperationID when adding route with multiple methods
Labels: question, question-migrate
### Discussed in https://github.com/fastapi/fastapi/discussions/8449

Originally posted by **bruchar1** March 30, 2022
### First Check

- [X] I added a very descriptive title to this issue.
- [X] I used the GitHub search to find a similar issue and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
router.add_api_route(
    "/clear",
    clear,
    methods=["POST", "DELETE"]
)
```

### Description

Seems to be caused by #4650.

The new `generate_unique_id()` function uses `list(route.methods)[0].lower()` as suffix for the `operation_id`. Therefore, in my example, both post and delete endpoints get `_post` suffix for operation_id, causing it to no longer be unique.

It then issues a "UserWarning: Duplicate Operation ID"

### Operating System

Windows

### Operating System Details

_No response_

### FastAPI Version

0.75.0

### Python Version

3.10.2

### Additional Context

_No response_

---
Comment: There is also PR #4851 that aimed to solve this, but it was closed by Sebastian with the [comment](https://github.com/fastapi/fastapi/pull/4851#issuecomment-2294657832):

> Using multiple methods for the same function is not actually supported. `@router.api_route()` is there as a semi-internal utility, and because Starlette supports multiple methods, the interface is there. But the official way to do it in FastAPI and have all the FastAPI features (including the automatic OpenAPI integration, with operation IDs) is by using the dedicated methods, like `app.post()`, `app.get()`, etc.

If we agree that `.api_route()` and `.add_api_route()` methods are semi-internal and shouldn't be used by user, we should probably turn them into private methods (add deprecation warning)?

```py
def add_route(...):
    warnings.warn(
        "This method is deprecated and will be removed in a future version. "
        "Please use `.get()`, `.post()`, etc.. methods instead.",
        DeprecationWarning,

---
Comment: There's a PR already for it: https://github.com/fastapi/fastapi/pull/10694/
---
Comment: I've seen `@api_route` suggested in this repo when you need to work with generic Requests (e.g. you want to create a proxy).


# Issue #13316: Callable object as dependency with body params is not parsing parameters inside `__call__` properly
When callable object is used as dependency, there is problem with parameters inside `__call__` method of object class. With following setup, you end up with query parameters instead of body parameters:

```python
class SomeModel(BaseModel):
    arg1: str

class SomeDependency:
    def __call__(
        self,
        some_model: Annotated[SomeModel, Body(..., description="Some model")],
    ) -> dict:
        print(some_model.arg1)

@app.post("/hello")
async def hello(data: Annotated[dict, Depends(SomeDependency())]):
    return data
```

Console:
```
pydantic.errors.PydanticUserError: `TypeAdapter[typing.Annotated[ForwardRef("Annotated[SomeModel, Body(..., description='Some model')]"), Query(PydanticUndefined)]]` is not fully defined; you should define `typing.Annotated[ForwardRef("Annotated[SomeModel, Body(..., description='Some model')]"), Query(PydanticUndefined)]` and all referenced types, then call `.rebuild()` on the instance.
```

`Query(PydanticUndefined)` makes no sense, there are no query parameters. But when this function (in `fastapi/dependencies/utils.py`) gets updated:

```python
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
    signature = inspect.signature(call)
    globalns = getattr(call, "__globals__", {})
    ...
```

into this:

```python
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
    signature = inspect.signature(call)
    if isinstance(call, type) or isinstance(call, types.FunctionType):
        globalns = getattr(call, "__globals__", {})
    else:
        globalns = getattr(call.__call__, "__globals__", {})
    ...
```

it works fine. Probably not the best solution. It's just to point out to the problem.

_Originally posted by @SobikXexe in https://github.com/fastapi/fastapi/discussions/13286#discussioncomment-12043516_


# Issue #13399: Dependency Models created from Form input data are loosing metadata(field set) and are enforcing validation on default values.
Labels: question

### Discussed in https://github.com/fastapi/fastapi/discussions/13380

Originally posted by **sneakers-the-rat** February 16, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

**Short version (UPD by @YuriiMotov):**

```python
from typing import Annotated

from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel

class ExampleModel(BaseModel):
    field_1: bool = True

app = FastAPI()

@app.post("/body")
async def body_endpoint(model: ExampleModel):
    return {"fields_set": list(model.model_fields_set)}

@app.post("/form")
async def form_endpoint(model: Annotated[ExampleModel, Form()]):
    return {"fields_set": list(model.model_fields_set)}

client = TestClient(app)

def test_body():
    resp = client.post("/body", json={})
    assert resp.status_code == 200, resp.text
    fields_set = resp.json()["fields_set"]
    assert fields_set == []  # Ok

def test_form():
    resp = client.post("/form", data={})
    assert resp.status_code == 200, resp.text
    fields_set = resp.json()["fields_set"]
    assert fields_set == []  # AssertionError: assert ['field_1'] == []
```

**Original code (in details):**

File: fastapi_defaults_bug.py
```python
import uvicorn
from typing import Annotated
from pydantic import BaseModel, Field

from fastapi import FastAPI, Form

class ExampleJsonModel(BaseModel):
    sample_field_1: Annotated[bool, Field(default=True)]
    sample_field_2: Annotated[bool, Field(default=False)]
    sample_field_3: Annotated[bool, Field(default=None)]
    sample_field_4: Annotated[str, Field(default=0)] # This is dangerous but can be used with a validator

class ExampleFormModel(BaseModel):
    sample_field_1: Annotated[bool, Form(default=True)]
    sample_field_2: Annotated[bool, Form(default=False)]
    sample_field_3: Annotated[bool, Form(default=None)]
    sample_field_4: Annotated[str, Form(default=0)] # This is dangerous but can be used with a validator

class ResponseSampleModel(BaseModel):
    fields_set: Annotated[list, Field(default_factory=list)]
    dumped_fields_no_exclude: Annotated[dict, Field(default_factory=dict)]
    dumped_fields_exclude_default: Annot
---
Comment: @sneakers-the-rat i think you are on the right spot, i do not have any role to expose what is the general preferred solution, this will be evaluated by reviewers and tiangolo.
What can i do, is express my personal opinion and what i think.
Based on your discussion i wrote a number of test cases to help anyone who want to work on this, to easily reproduce the issue and at the same time see what is the expected behaviour.

About Pydantic compatibility:
 v1, v2, v1 submodule of v2 should all be handled and sometimes this could be a bit tricky.

About the issue: while preloading the default values could be considered part of the root cause, for me the real problem is that we are loosing the information about if a field has been set or not and other corner cases that have to deal with default and validation ( this will generate other issues including your original one ).

@Warlord-10 if you want to contribute look at: https://fastapi.tiangolo.com/contributing/

@async-shreyas
You spotted
---
Comment: Ok great, I'll write a PR now.

@async-shreyas yes, see the prior discussion at https://github.com/fastapi/fastapi/discussions/13380
---
Comment: from fastapi import Form
from pydantic import BaseModel

class User(BaseModel):
    name: str = "default"


# Issue #13400: Header parameter and model handling does not work as expected
Labels: bug

### Discussed in https://github.com/fastapi/fastapi/discussions/13160

Originally posted by **freud14-tm** January  6, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from typing import Annotated, TypeAlias

from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()

class CommonHeaders(BaseModel):
    host: str
    save_data: bool
    if_modified_since: str | None = None
    traceparent: str | None = None
    x_tag: list[str] = []

CommonHeadersAnnotated: TypeAlias = Annotated[CommonHeaders, Header()]

@app.get("/items/")
async def read_items(headers: CommonHeadersAnnotated):
    return headers

@app.get("/items2/")
async def read_items2(x_prd_code: Annotated[str, Header()], headers: CommonHeadersAnnotated):
    return headers
```

### Description

There seems to be a few problems when using [Header Parameter Models](https://fastapi.tiangolo.com/tutorial/header-param-models/) as documented. The code above and the screenshots bellow show it. First, it seems that the Swagger UI doesn't convert underscores into dashes when using a Header Parameter Model. It works fine otherwise. Second, when using another header in the function, FastAPI interprets the parameter model as an object to be sent as a single header with the parameters as a comma-separated list instead of expecting the single parameters.

![image](https://github.com/user-attachments/assets/7f387f1d-e737-492a-98ae-752dafa7438b)

![image](https://github.com/user-attachments/assets/30e5eaea-2d5f-4595-b989-46fb6bf89e00)

### Operating System

Linux

### Operating System Details

_No response_

### FastAPI Version

0.115.6

### Pydantic Version

2.10.4

### Python Version

3.11.0

### Additional Context

_No response_

---
Comment: Thanks for the discussion, everyone!

Let's split this into two things.

The first, handling correctly `convert_underscores`, this is a bug, let's keep this issue for that. It should have been handled in https://github.com/fastapi/fastapi/pull/13515 🎉

This will be released in the next version, `0.115.12`, in the next hours.

The new docs: https://fastapi.tiangolo.com/tutorial/header-param-models/#forbid-extra-headers

---

About having a model alongside another parameter, this would be a feature request, better in a new discussion.

I'm also not sure about it, because it would behave differently from a body parameter alongside a body model. So I would have to think about that feature some more first. For now, when using a Pydantic model for headers, only one model per path operation is supported.

Anyway, feel free to create a new discussion question with the feature request. 🤓
---
Comment: Ah, then it's a bug. Sorry.
---
Comment: I'll look into cleaning up the code to fit more within the `analyze_param` function and then could look into creating a PR for it


# Issue #13440: Validations in `Annotated` like `AfterValidator` do not work in FastAPI 0.115.10
Labels: bug

### Discussed in https://github.com/fastapi/fastapi/discussions/13431

Originally posted by **amacfie-tc** February 28, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from typing import Annotated

from pydantic import AfterValidator
from fastapi import FastAPI

app = FastAPI()

def validator(v):
    raise ValueError()

Ints = Annotated[list[int], AfterValidator(validator)]

@app.post("/")
def post(ints: Ints) -> None:
    return None
```

### Description

If we run the code and send a request to the endpoint, e.g.
```
echo -n '[2,3,4]' | http POST http://localhost:8000
```
on version 0.115.9, we get a 422 but on 0.115.10 we get 200. Is this a bug?

### Operating System

Linux

### Operating System Details

_No response_

### FastAPI Version

0.115.10

### Pydantic Version

2.9.2, 2.10.6

### Python Version

3.12

### Additional Context

_No response_

---

@tiangolo writes:

This was introduced here: https://github.com/fastapi/fastapi/pull/13314

I'm currently investigating and a fix will be released shortly.

The problem is only when using `Annotated` directly in FastAPI parameters, when used inside of Pydantic models the validators work (raise) as expected:

```Python
from typing import Annotated

from fastapi import FastAPI
from pydantic import AfterValidator, BaseModel

app = FastAPI()

def validator(v):
    raise ValueError()

Ints = Annotated[list[int], AfterValidator(validator)]

class Model(BaseModel):
    ints: Ints

@app.post("/")
def post(ints: Model) -> None:
    return None
```
---
Comment: Cool :)
---
Comment: This was handled in https://github.com/fastapi/fastapi/pull/13442

That reverted the PR that introduced the problem, and added docs for these specific use cases, including source examples and tests for them to ensure they keep being supported. 🤓

It is available in FastAPI 0.115.11, just released. 🚀


# Issue #13471: Basic auth `realm` is REQUIRED but handled as optional
Labels: bug
According to https://datatracker.ietf.org/doc/html/rfc7617#autoid-3 , specification of the `realm` parameter is REQUIRED, so making `realm` optional here

https://github.com/fastapi/fastapi/blob/643d2845de09a437b955a163ab25eb0887bfd0e1/fastapi/security/http.py#L195

and at related places, is misleading and makes it easy to create non-conforming APIs. It bit me when a Shelly device refused (rightfully) to authenticate against the API which was using the default (missing) `realm` behavior.

---
Comment: I think we should close this issue.

As Sebastian mentioned in [this comment](https://github.com/fastapi/fastapi/pull/13786#pullrequestreview-3501695067), `realm` seems to be not required in latest version of RFC.

> I also noted that the spec says that the realm is now optional, but only in a footer note (https://datatracker.ietf.org/doc/html/rfc7235#appendix-A). 😂 Anyway, we are good with that now.

I checked this and agree:

The https://datatracker.ietf.org/doc/html/rfc7617#autoid-3 states:

> The authentication parameter 'realm' is REQUIRED ([RFC7235], Section 2.2).

But if we go to Section 2.2 of RFC7235, we have:

> [2.2](https://datatracker.ietf.org/doc/html/rfc7235#section-2.2).  Protection Space (Realm)
>
>    The "realm" authentication parameter is reserved for use by
>    authentication schemes that wish to indicate a scope of protection.
>
>    A protection space is defined by the canonical root URI (the scheme
>    and authority components of the effective request URI;
---
Comment: Yeah this does look like a mistake  to have "realm" as optional
---
Comment:  looks to be getting fixed here https://github.com/fastapi/fastapi/pull/12507


# Issue #13533: Multiple regressions in the handling of forms & form validation
Labels: bug

### Issue Content

We have found at least 2 regression in the way forms are handled while trying to migrate to v0.115.11 from version v0.112.4. After investigation we were able to identify 2 commits that introduce 2 separate bugs that break the handling of default values in both `x-form-urlencoded` and `mutlipart` froms. Partial fixes have been proposed that also address a CVE, but the PR has been hanging since october 24.

# Breaking in the handling of default value in `x-url-encoded` forms

This bug has been introduced in https://github.com/fastapi/fastapi/pull/12134.

MRE:
```python
app = FastAPI()

@app.post("/")
def root(
    name: Annotated[Optional[str], Form(embed=True)] = None,
):
    print(name)
    return name
```

with the following request:
```
❯ http post -v --form localhost:8888 name=""
POST / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, br, zstd
Connection: keep-alive
Content-Length: 5
Content-Type: application/x-www-form-urlencoded
Host: localhost:8888
User-Agent: xh/0.24.0

name=

HTTP/1.1 200 OK
Content-Length: 2
Content-Type: application/json
Date: Sun, 23 Mar 2025 21:01:49 GMT
Server: uvicorn

""
```
The expected result is that `None` is printed, but instead `""` is printed.

this is the offending bit from the linked PR:
```
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index 6083b731..db7eedba 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -789,9 +789,9 @@ async def _extract_form_body(
             value = serialize_sequence_value(field=field, value=results)
         if value is not None:
             values[field.name] = value
-    for key, value in received_body.items():
-        if key not in values:
-            values[key] = value
+    # for key, value in received_body.items():
+    #     if key not in values:
+    #         values[key] = value
     return values
```
This patch solves the x-form-urlencoded  case. So we indeed have two different regressions.
This _get_multi_dict_value  gets called for all fields in the schema: https://github.com/fastapi/fastapi/blob/4633b1bca933e68dac5c3bcce797ff5963debe2a/fastapi/dependencies/utils.py#L765-L765
we see here the special case for empty fields: https://github.com/fastapi/fastapi/blob/4633b1bca933e68dac5c3bcce797ff5963debe2a/fastapi/dependencies/utils.py#L695-L700
This bit here just blindly re-adds all fields from the body:    https://github.com/fastapi/fastapi/blob/4633b1bca933e68dac5c3bcce797ff5963debe2a/fastapi/dependencies/utils.py#L794-L796

This would be partially fixed by https://github.com/fastapi/fastapi/pull/12502/files, but also requires that ignored fields are not re-added to the form.

# Breaking in the handling of default value in `multipart` forms

The breaking of multipart form originates from https://github.com/fastapi/fastapi/pull/12117 where the check for empty field was dropped https://github.com/fastapi/fastapi/pull/12117/files#diff-aef3dac481b68359f4edd6974fa3a047cfde595254a4567
---
Comment: @alv2017 take the following example, this is the `x-www-form-urlencoded` case:

```python
from typing import Annotated, Optional
import fastapi

app = fastapi.FastAPI()

@app.post("/")
def root(
    age: Annotated[Optional[int], fastapi.Form()] = None,
):
    print(age)
    return age

```

running the following command:
```
curl -v  -X POST http://localhost:8888/ --data-urlencode 'age='
```

with fastapi `0.112.4`

```
Note: Unnecessary use of -X or --request, POST is already inferred.
* Host localhost:8888 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
*   Trying [::1]:8888...
* connect to ::1 port 8888 from ::1 port 55215 failed: Connection refused
*   Trying 127.0.0.1:8888...
* Connected to localhost (127.0.0.1) port 8888
> POST / HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/8.7.1
> Accept: */*
> Content-Length: 4
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 4 bytes
< HTTP/1.1 200 OK
< date: Mon, 24 Mar 2025 18:57:03 GMT
< server: uvicorn
< c
---
Comment: Also note that it's only for forms, json bodies work as intended
---
Comment: > Also note that it's only for forms, json bodies work as intended

Correction added. :smiley:

It would be good if you could show the code, that you are using with http clients. Maybe the test that was passing before, and that is failing after upgrading to the newer version?


# Issue #13606: FastAPI Tensor flow and tensor flow lite issue with Pyhon v3.14.x when making a pip installtion bug
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

I'm running a FastAPI backend and a frontend in flutter . After upgrading python version to v3.14.x, i was unable to install tensorflow or tensorflow lite for my project
please check out the issue to fix

Downgrading python to v3.14.x fixed it.
---
Comment: not resolved yet
---
Comment: Please create a discussion.


# Issue #13715: SUB APPLICATIONS - MOUNTS IS SHOW INCORRECT INFORMATION
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

Hi,

I'm checking the docs: https://fastapi.tiangolo.com/advanced/sub-applications/#check-the-automatic-api-docs

I see this example:

![Image](https://github.com/user-attachments/assets/12381416-ea90-46c8-bc0d-bf1f38fbc9ec)

but when I test in my local machine. I see it:

![Image](https://github.com/user-attachments/assets/347a24d3-edb2-439c-b3cc-afe4875d0783)

Am I doing some bad?

Thanks.


# Issue #13839: API Big file attacks
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

Any POST interface, submitting a file request (even if the interface does not declare to accept file parameters) causes the service memory to expand until the service crashes


# Issue #13880: Support for propertyNames in OpenAPI schema when using dict[Enum, ...] with Pydantic v2
When using dict[StrEnum, ...] or RootModel[dict[StrEnum, ...]] in a FastAPI app with Pydantic v2, the generated OpenAPI schema does not enumerate the enum values used as dictionary keys. Instead, the UI shows [any-key], which does not reflect the actual constraints.

As of Pydantic v2.11+, support for emitting propertyNames with enum constraints was added via [PR #10478](https://github.com/pydantic/pydantic/pull/10478). This allows OpenAPI/JSON Schema to correctly express restrictions on object keys, such as:

```
{
  "type": "object",
  "propertyNames": {
    "type": "string",
    "enum": ["foo", "bar"]
  },
  "additionalProperties": {
    "type": "integer"
  }
}
```

However, FastAPI currently does not appear to consume or propagate the propertyNames node from Pydantic’s schema output, so these constraints are missing in the OpenAPI spec and Swagger UI.

### Expected Behavior

FastAPI should correctly include propertyNames in the generated OpenAPI schema when dict[Enum, T] is used as a request/response model with Pydantic v2. This would allow Swagger UI to better reflect the allowed dictionary keys.

### To Reproduce
```
from enum import StrEnum
from pydantic import RootModel
from fastapi import FastAPI

class MyEnum(StrEnum):
    foo = "foo"
    bar = "bar"

class MyModel(RootModel[dict[MyEnum, int]]):
    pass

app = FastAPI()

@app.post("/test")
def test_endpoint(model: MyModel):
    return model
```

### Resulting OpenAPI Schema:
```
{
  "type": "object",
  "additionalProperties": {
    "type": "integer"
  }
}
```

### Expected Schema (from Pydantic v2.11+):
```
{
  "type": "object",
  "propertyNames": {
    "type": "string",
    "enum": ["foo", "bar"]
  },
  "additionalProperties": {
    "type": "integer"
  }
}
```

### Environment
- FastAPI version: latest
- Pydantic version: 2.11.x+
- Python version: 3.10+
- Swagger UI version: [auto-generated by FastAPI]
---
Comment: Hi! I'm trying to reproduce this behavior using:

Pydantic version: 2.11.7

Python version: 3.11.13

Here’s the relevant snippet from the generated OpenAPI schema:

```yaml
"MyEnum": {
  "type": "string",
  "enum": ["foo", "bar"],
  "title": "MyEnum"
},
"MyModel": {
  "additionalProperties": {
    "type": "integer"
  },
  "propertyNames": {
    "$ref": "#/components/schemas/MyEnum"
  },
  "type": "object",
  "title": "MyModel"
}
```

Is this the expected output? Or am I missing something?

Apologies if this is a basic question — still getting familiar with how all of this fits together.

Thanks!
---
Comment: I checked it and on current FastAPI (1.116.1) and Pydantic (2.11.7) versions it gives me schema with `propertyNames`.
It uses reference to `MyEnum`, but it seems to me that it's Ok (it doesn't change anything if I change it to the schema from the issue text).

Swagger shows schema correctly, but struggles to create correct example and doesn't validate input on UI side:

So, I think this is not an issue on FastAPI's side and we should close it.

@andrzejdoros, could you please check it?
---
Comment: pip install --upgrade fastapi pydantic


# Issue #14010: validate_core_schema has been removed in the new pydantic-core (>=2.35.0), causing FastAPI to fail to import. Hoping to resolve this.
### Privileged issue

- [ ] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

validate_core_schema has been removed in the new pydantic-core (>=2.35.0), causing FastAPI to fail to import. Hoping to resolve this.

fastapi==0.116.1
pydantic_core==2.39.0


# Issue #14078: AI Bug Analysis: ValidationError: 1 validation error for Request
body
  field required (type=value_error.missing)
### 🤖 AI Bug Report

**Original Error:**
```
ValidationError: 1 validation error for Request
body
  field required (type=value_error.missing)
```

---

### 🔬 Root Cause Analysis
The error message `ValidationError: 1 validation error for Request body field required (type=value_error.missing)` indicates that the request made to the server is missing a required field in the body of the request. This type of error typically occurs in the context of using Pydantic models with FastAPI, where the models define the expected structure and content of request bodies. Pydantic models enforce type checks and required fields, and if a request does not meet these criteria, a `ValidationError` is raised.

Given the context provided, it seems that the error is related to handling requests in a FastAPI application. The documents referenced in the code context discuss handling errors in FastAPI, including `RequestValidationError` and `ValidationError`, which are crucial for understanding how FastAPI processes and validates incoming request data against Pydantic models.

The specific error message points to a missing field in the request body, which is required by the Pydantic model that validates the request. This could be due to several reasons:

1. **Client-Side Issue**: The client making the request may have failed to include a necessary field in the request body. This is common when the client's code does not correctly assemble the request or when the user forgets to provide all the required information.

2. **Server-Side Validation Logic**: On the server side, the Pydantic model expects a field that was not provided in the request. This indicates a mismatch between the client's understanding of the required request format and the server's expectations.

3. **Documentation/Communication Gap**: If the API documentation or the communication between the frontend and backend teams is not clear, it might lead to misunderstandings about what data is required, leading to such validation errors.

4. **Code Changes**: Changes in the backend code, such as updating Pydantic models without corresponding updates in the client code, can also lead to such errors if the new requirements are not communicated or documented.

To resolve this issue, one should:

- Verify the Pydantic model on the server side to understand exactly which field is missing.
- Check the client's request to ensure it includes all required fields as per the Pydantic model.
- Ensure that the API documentation is up to date and accurately reflects the current requirements of the Pydantic model.
- If the error persists, additional logging on the server side to capture incoming requests might help identify what is missing or misformatted in the request body.

---

### 🛠 Suggested Fix
Given the root cause analysis, the error stems from a missing required field in the request body when it's being validated against a Pydantic model in a FastAPI application. To address this issue, we need to ensure that the c


# Issue #14114: how is this code is relavent to this ?
> Here's another repro:
>
> ```python
> from __future__ import annotations
>
> from typing import TYPE_CHECKING, Annotated
>
> from fastapi import Depends, FastAPI
> from fastapi.testclient import TestClient
>
> if TYPE_CHECKING:
>     from httpx import AsyncClient
>
> app = FastAPI()
>
>
> @app.get("/test")
> async def ping(client: Annotated[AsyncClient, Depends(lambda: AsyncClient())]) -> str:
>     resp = await client.get('http://example.com')
>     resp.raise_for_status()
>     return f"Got {len(resp.text)} bytes"
>
>
>
> async def test() -> None:
>     from httpx import AsyncClient
>
>     async with AsyncClient() as client:
>         client = TestClient(app)
>
>         response = client.get("/test")
>         assert response.status_code == 200, f"{response.status_code=}: {response.text=}"
>
>
> if __name__ == "__main__":
>     import anyio
>
>     anyio.run(test)
> ```

 _Originally posted by @adriangb in [#13056](https://github.com/fastapi/fastapi/issues/13056#issuecomment-2616362994)_


# Issue #14128: AssertionError: fastapi_inner_astack not found in request scope
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

latest version of Fastapi is not support with Starlette 0.48.0.

FAFastAPI 0.118.0
Starlette 0.48.0
---
Comment: > [@tiangolo](https://github.com/tiangolo) [@Kludex](https://github.com/Kludex) hello, this error ocurrs when paginating resuts:
>
> from fastapi_pagination import Page from fastapi_pagination.ext.sqlalchemy import paginate
>
> @contents_router.get( "", response_model=Page[UploadedContentResponse], status_code=status.HTTP_200_OK, tags=["Contents"], )
>
> Is there any solution for this issue?

Just in case someone else stumbles upon this error - it's solved with `fastapi-pagination` v0.14.2 [[link](https://github.com/uriyyo/fastapi-pagination/issues/1599)]
---
Comment: btw, this is an MRE:
```py
from fastapi import APIRouter
from starlette.testclient import TestClient

router = APIRouter()

@router.get("/items")
async def root():
    return "hi"

client = TestClient(router)
client.get("/items")
```
---
Comment: > this error ocurrs when paginating resuts:

Please, report this in the repository of `fastapi_pagination` package that you are using


# Issue #14199: Se que ha pasado mucho tiempo, soy ingeniero y Senior en Desarrollo de Software, creo que  hay demasiado factores para que un código sea más rápido, o se note lento:
Se que ha pasado mucho tiempo, soy ingeniero y Senior en Desarrollo de Software, creo que  hay demasiado factores para que un código sea más rápido, o se note lento:
a) El hadware.
b) La internet.
c) Puede haber un virus.
d) La memoria esta muy ocupada,
e) etc. etc.

FastApi, es simplemente una arquitectura, y de paso creo desconoce que en  Python puede emplearse como una consola de servicio, mediante la libreria de PyCharm, que es algo totalmente distinto API Rest. por que es una arquitectura que debes diseñar con mucho criterio. Esto le permitiría tener administración correcta de los recursos eliminar cualquier tasa latencia, si es lo que están evaluando.
De todas maneras no existe un mejor lenguaje de programación, para arquitecturas complejas de datos si no el mismo DBC, mediante procedimiento almacenado, y si quieren algo más complejo componente desarrollado en C++.
Con un componente (Librería Dinámica), es que postgres puede generar Vectores Embedding. Imaginase  una fuerte lógica de negocios.

Saludos;

_Originally posted by @Joseg212 in https://github.com/fastapi/fastapi/discussions/7320#discussioncomment-14469070_


# Issue #142: ApiKey Header documentation
Labels: docs, confirmed, reviewed
Hi,

Do you have some documentation or example regarding configuration for ApiKey (header) and how to verify it on FastAPI ?

thanks in advance,

Rémy.
---
Comment: I ended up working it out, here's how i solved the problem

security.py
```python
from fastapi import Depends, HTTPException
from fastapi.security import APIKeyHeader
from starlette import status

X_API_KEY = APIKeyHeader(name='X-API-Key')

def check_authentication_header(x_api_key: str = Depends(X_API_KEY)):
    """ takes the X-API-Key header and converts it into the matching user object from the database """

    # this is where the SQL query for converting the API key into a user_id will go
    if x_api_key == "1234567890":
        # if passes validation check, return user data for API Key
        # future DB query will go here
        return {
            "id": 1234567890,
            "companies": [1, ],
            "sites": [],
        }
    # else raise 401
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid API Key",
    )
```

main.py
```python
...
from fastapi import APIRouter, Depends
from mod
---
Comment: if api_key is not necessary in the endpoint you can go for
```Python
from fastapi import Security
from fastapi.security.api_key import APIKeyHeader

API_KEY = "1234567asdfgh"
API_KEY_NAME = "X-API-KEY"

api_key_header_auth = APIKeyHeader(name=API_KEY_NAME, auto_error=True)

async def get_api_key(api_key_header: str = Security(api_key_header_auth)):
    if api_key_header != API_KEY:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API Key",
        )

@router.get('/health', dependencies=[Security(get_api_key)])
async def endpoint():
```
---
Comment: Thanks @wshayes for your help here! Much appreciated as always :tada:

@meandus if you can use OAuth2, that tutorial and the project generator might help. If somehow you explicitly need something different than OAuth2, with some custom APIKeyHeader (as defined in OpenAPI), yes, it is supported, but it is not properly documented yet.

I suggest you check the security section in the docs shared by William, and after knowing how it works, if you need to explicitly use `APIKeyHeader` instead of OAuth2, you can `from fastapi.security.api_key import APIKeyHeader`.

At least while I update the docs with those specifics... :grin:


# Issue #14221: Changes to _remap_definitions_and_field_mappings failing in v0.119
Hello there! I just noticed that recent changes to

https://github.com/fastapi/fastapi/blame/cb7018d782c88b189f11d6141c8231ffb9b403b0/fastapi/_compat/v2.py#L273 in v0.119.0

Started showing up as errors like:

```python
    def _remap_definitions_and_field_mappings(
        *,
        model_name_map: ModelNameMap,
        definitions: Dict[str, Any],
        field_mapping: Dict[
            Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
        ],
    ) -> Tuple[
        Dict[Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
        Dict[str, Any],
    ]:
        old_name_to_new_name_map = {}
        for field_key, schema in field_mapping.items():
            model = field_key[0].type_
            if model not in model_name_map:
                continue
            new_name = model_name_map[model]
>           old_name = schema["$ref"].split("/")[-1]
                       ^^^^^^^^^^^^^^
E           KeyError: '$ref'

(...)

 field_mapping = {(ModelField(field_info=Body(PydanticUndefined), name='body', mode='validation'), 'validation'): {'$ref': '#/component...validation'), 'validation'): {'$ref': '#/components/schemas/xyz__apps__api__preferences__integrations__Body'}, ...}
```
---
Comment: Do you have an MRE?
---
Comment: In my case the error is similar but with the `.split()` method.

```
  File ".venv/lib/python3.12/site-packages/fastapi/_compat/v2.py", line 245, in _replace_refs
    ref_name = schema["$ref"].split("/")[-1]
               ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'split'
```
---
Comment: Do you have an MRE?


# Issue #14225: docs: Fix typo in tutorial documentation
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

## Description
Fixed a minor typo in the tutorial documentation to improve clarity and readability.

## Changes
- Fixed typo: "recieve" → "receive" in `docs/en/docs/tutorial/body.md`
- Line 45: Updated documentation for better accuracy

## Checklist
- [x] Typo verified against proper spelling
- [x] No code changes, documentation only
- [x] Follows existing documentation style

This small fix helps new users better understand the tutorial.


# Issue #14247: Component name regression in OpenAPI spec for v0.119.0
Labels: bug
Adding the issue here for completeness, although most of the conversation is in the GitHub Discussion.

### Discussed in https://github.com/fastapi/fastapi/discussions/14177

Originally posted by **walsha2** October 12, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from enum import StrEnum

from fastapi import FastAPI
from pydantic import BaseModel, Field

class MessageEventType(StrEnum):
    alpha = "alpha"
    beta = "beta"

class MessageEvent(BaseModel):
    event_type: MessageEventType = Field(default=MessageEventType.alpha)
    output: str

class MessageOutput(BaseModel):
    body: str = ""
    events: list[MessageEvent]

class Message(BaseModel):
    id: str
    input: str
    output: MessageOutput

app = FastAPI(title="Minimal FastAPI App", version="1.0.0")

@app.post("/messages", response_model=Message)
async def create_message(input_message: str) -> Message:
    return Message(
        input=input_message,
        output=MessageOutput(body=f"Processed: {input_message}"),
    )

if __name__ == "__main__":
    openapi_spec = app.openapi()
    for c in list(openapi_spec.get("components", {}).get("schemas", {}).keys()):
        print(c)
```

### Description

## Issue Summary

Take the minimal example provided above, run with `fastapi==0.118.3` and it will produce:

```
HTTPValidationError
Message
MessageEvent
MessageEventType
MessageOutput
ValidationError
```

Now run the same code with `fastapi==0.119.0` and it will produce:

```
HTTPValidationError
Message
MessageEvent
MessageEventType
MessageOutput-Input
MessageOutput-Output
ValidationError
```

Note how `MessageOutput` is now suffixed unnecessarily as: `MessageOutput-Input` and `MessageOutput-Output`. This seems unexpected considering the changes made between   `v0.118.3` and `v0.119.0`

## Minor Tweak

One minor tweak to the example and this issue goes away. Remove the enum from `MessageEvent`:

```python
class MessageEvent(BaseModel):
    output: str
```

Run again and the issue is no longer there.

```
HTTPValidationError
Message
MessageEvent
MessageOutput
ValidationError
```

## TLDR

Why does the presence of an enum value on `MessageEvent` create a bifur
---
Comment: It should be fixed in https://github.com/fastapi/fastapi/pull/14246, just relased in FastAPI 0.120.2. :tada:


# Issue #14271: 🐛 0.120.3 breaks `SecurityBase` based dependencies in OpenAPI
Labels: bug
Edit: Added as an issue for completeness and history.

### Discussed in https://github.com/fastapi/fastapi/discussions/14263

Originally posted by **oldfielj-ansto** October 31, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from uvicorn import run
from fastapi import FastAPI, Depends
from fastapi.security import OpenIdConnect

_oidc = OpenIdConnect(
    openIdConnectUrl="https://localhost/auth/realms/test/.well-known/openid-configuration",
)

app = FastAPI(
    title="My Application",
    docs_url="/swagger",
    redoc_url="/docs",
    openapi_url="/openapi.json",
    dependencies=(Depends(_oidc),),
)

@app.get("/")
async def hello_world():
    return {"Hello": "World"}

if __name__ == "__main__":
    run(app=app, port=8080)
```

### Description

# Under FastAPI **0.120.2**

* Run the example code and navigate to [http://localhost:8080/swagger](http://localhost:8080/swagger)
* Notice that the green "Authorize" button is present and user can choose to authenticate a session, padlock icon is also present on root endpoint.
* Calling the endpoint normally without user being authorized, results in expected 403 status.

# Under FastAPI **0.120.3**

* Run the example code and navigate to [http://localhost:8080/swagger](http://localhost:8080/swagger)
* Notice that the green "Authorize" button is missing and user cannot choose to authenticate a session, padlock icon is also missing on root endpoint.
* Calling the endpoint normally without user being authorized, results in expected 403 status.

As well as testing `Depends` I have tested with `Security` to declare the dependency, which results in the same behavior.

What I'd expect is that FastAPI **0.120.3** displays consistent behavior with FastAPI **0.120.2**, when defining a security dependency, and that the "Authorize" button and padlock icon on the root endpoint would be displayed in the auto generated Swagger documentation.

It would seem that in **0.120.3**, the security section of the generated `openapi.json` file is omitted.

## Under FastAPI **0.120.2**
```json
{
  "openapi": "3.1.0",
  "info": {
    "title": "My Application",
    "version": "0.1.0"
  },
  "paths": {
    "
---
Comment: This was solved by @YuriiMotov in https://github.com/fastapi/fastapi/pull/14266. It was just released in FastAPI 0.120.4. :rocket: :tada:


# Issue #14312: CORS Middleware and exception handler
the MRE is at [https://github.com/4tst/mre-exception-handler](https://github.com/4tst/mre-exception-handler).

without `@exception_handler(ValueError)`, then will appear CORS error when request sub-route,
for more detail, please click [here](https://github.com/4tst/mre-exception-handler)


# Issue #14316: `Depends(func, scope="function")` with `yield` dependency exits after the request is sent instead of after the function
Labels: bug
Adding this issue for completeness.

Solved by: https://github.com/fastapi/fastapi/pull/14301

### Discussed in https://github.com/fastapi/fastapi/discussions/14296

Originally posted by **guldfisk** November  5, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from types import NoneType
from typing import Iterator, Annotated

from fastapi import APIRouter
from fastapi import Depends
from fastapi import FastAPI

app = FastAPI()

class ApplicationError(Exception): ...

def dependency_with_cleanup_error() -> Iterator[None]:
    yield
    raise ApplicationError()

router = APIRouter(
    dependencies=[Depends(dependency_with_cleanup_error, scope="function")]
)

@router.get("/broken")
def broken():
    # Will return 200, and then fail in the cleanup.
    return {"status": "ok"}

@router.get("/works")
def endpoint(
    v: Annotated[NoneType, Depends(dependency_with_cleanup_error, scope="function")],
):
    # Will correctly return 500
    return {"status": "ok"}

app.include_router(router)
```

### Description

When using the new "scope" feature for yield dependencies, function scope is still cleaned up after the response is sent, if the dependency is requested in the api router, instead of on the path function.

Maybe this is a feature, as in "function" should be interpreted as the scope of where the dependency is requested, and not always the path function, but I can't find any documentation mentioning this behavior, and in any case I'm not sure what the usecase for that would be.

### Operating System

Linux

### Operating System Details

_No response_

### FastAPI Version

0.121.0

### Pydantic Version

2.12.3

### Python Version

3.11.12

### Additional Context

_No response_

---
Comment: This was solved by https://github.com/fastapi/fastapi/pull/14301, released in FastAPI 0.121.1. 🐛


# Issue #14344: AttributeError: 'dict' object has no attribute 'split'
Labels: bug, answered
Minimum Reproducible Example:

```py
# /// script
# dependencies = [
#   "pydantic",
#   "fastapi[standard]",
#   "starlette",
# ]
# ///

import pydantic
import starlette
import fastapi
from fastapi import FastAPI
import sys
from pydantic import BaseModel, Field, ConfigDict

# print the dependencies to stdout, one per line
print(f'pydantic version = {pydantic.__version__}')
print(f'starlette version = {starlette.__version__}')
print(f'fastapi version = {fastapi.__version__}')
# print python version
print(f'Python version = {sys.version}')

app = FastAPI(title='Logfire')

class ModelWithRef(BaseModel):
    ref: str = Field(validation_alias='$ref', serialization_alias='$ref')
    model_config = ConfigDict(validate_by_alias=True, serialize_by_alias=True)

@app.get('/')
async def read_root() -> ModelWithRef:
    return ModelWithRef(ref='some-ref')

print(app.openapi())
```

Run with `uv run main.py`.

Error:

```bash
❯ uv run main.py
Installed 42 packages in 61ms
pydantic version = 2.12.4
starlette version = 0.49.3
fastapi version = 0.121.1
Python version = 3.10.15 (main, Oct 16 2024, 08:33:15) [Clang 18.1.8 ]
Traceback (most recent call last):
  File "/Users/marcelotryle/dev/main.py", line 36, in <module>
    print(app.openapi())
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/applications.py", line 1060, in openapi
    self.openapi_schema = get_openapi(
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/openapi/utils.py", line 504, in get_openapi
    field_mapping, definitions = get_definitions(
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/main.py", line 292, in get_definitions
    v2_field_maps, v2_definitions = v2.get_definitions(
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py", line 249, in get_definitions
    new_mapping, new_definitions = _remap_definitions_and_field_mappings(
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py", line 331, in _remap_definitions_and_field_mappings
    new_value = _replace_refs(
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py", line 273, in _replace_refs
    new_schema[key] = _replace_refs(
  File "/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py", line 265, in _replace_refs
    ref_name = schema["$ref"].split("/")[-1]
AttributeError: 'dict' object has no attribute 'split'
```

---
Comment: See also: https://github.com/fastapi/fastapi/discussions/14196
---
Comment: This should be fixed by https://github.com/fastapi/fastapi/pull/14349, released in FastAPI 0.121.2 🎉


# Issue #14431: FastAPI app with `separate_input_output_schemas` disabled excludes computed fields on Pydantic models from OpenAPI output
Labels: bug
Adding the issue for completeness.

Solved in https://github.com/fastapi/fastapi/pull/13207

### Discussed in https://github.com/fastapi/fastapi/discussions/10342

Originally posted by **ldthorne** September 27, 2023
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
import pytest
from fastapi import FastAPI
from starlette.testclient import TestClient

@pytest.fixture(name="client")
def get_client():
    app = FastAPI(separate_input_output_schemas=False)

    from pydantic import BaseModel, computed_field

    class Rectangle(BaseModel):
        width: int
        length: int

        @computed_field
        @property
        def area(self) -> int:
            return self.width * self.length

    @app.get("/")
    def read_root() -> Rectangle:
        return Rectangle(width=3, length=4)

    client = TestClient(app)
    return client

def test_get(client: TestClient):
    response = client.get("/openapi.json")
    data = response.json()

    rectangle_model = data["components"]["schemas"]["Rectangle"]["properties"]

    assert "area" in rectangle_model.keys()
```

### Description

I expect that even with `separate_input_output_schemas` set to `False` the OpenAPI schema includes computed fields declared on a Pydantic model

### Operating System

macOS

### Operating System Details

_No response_

### FastAPI Version

0.103.1

### Pydantic Version

2.4.1

### Python Version

3.8.16

### Additional Context

I think it may come from [here](https://github.com/tiangolo/fastapi/blob/073e7fc950f1af24634b304afbb34bf212756dff/fastapi/_compat.py#L186)

---
Comment: Fixed by https://github.com/fastapi/fastapi/pull/13207

Available in FastAPI 0.123.4, released in the next few hours.


# Issue #14444: FastAPI 0.123.5 breaks async wrappers using @wraps
Labels: bug
(Already being worked on)

### Discussed in https://github.com/fastapi/fastapi/discussions/14442

Originally posted by **falkoschindler** December  3, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from functools import wraps
import uvicorn
from fastapi import FastAPI

app = FastAPI()

def my_decorator(func):
    """A decorator that wraps a sync function with an async handler."""

    @wraps(func)
    async def wrapper():
        func()
        return 'OK'

    return wrapper

@app.get('/')
@my_decorator
def index():
    """A simple sync page function."""
    print('Hello!')

if __name__ == '__main__':
    uvicorn.run(app)
```

### Description

* Visit "/".
* You'll see "Internal Server Error".
* A ValueError appears:
    ```
    ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
    ```

Since FastAPI 0.123.5 (PR #14434), using `functools.wraps` on an async wrapper around a sync function causes FastAPI to incorrectly treat the handler as sync, resulting in: `ValueError: [TypeError("'coroutine' object is not iterable"), ...]`

The issue is that `Dependant.is_coroutine_callable` now uses `inspect.unwrap()` which follows `__wrapped__` back to the original sync function, instead of checking if the actual registered handler is async.

### Operating System

macOS

### Operating System Details

_No response_

### FastAPI Version

0.123.5

### Pydantic Version

2.12.5

### Python Version

3.11.11

### Additional Context

_No response_

---
Comment: This should be fixed by https://github.com/fastapi/fastapi/pull/14448

It's now released in FastAPI 0.123.6 :tada:


# Issue #14454: OAuth2 security schemes duplicated in OpenAPI, with and without scopes, when used at the router level
Labels: bug
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

OAuth2 security schemes duplicated in OpenAPI, with and without scopes, when used at the router level

Reported by @Kludex on another channel 🙌

(I'm working on it)

```Python
# /// script
# dependencies = [
#   "fastapi[standard]==0.121.3",
# ]
# ///

import json
import sys
from typing import Annotated

import fastapi
from fastapi import APIRouter, Depends, FastAPI, Security
from fastapi.security import OAuth2AuthorizationCodeBearer, SecurityScopes

# print the dependencies
print(f'fastapi version = {fastapi.__version__}')
print(f'Python version = {sys.version}')

app = FastAPI()

oauth2_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl='api/oauth/authorize',
    tokenUrl='/api/oauth/token',
    refreshUrl='/api/oauth/token',
    auto_error=False,
    scopes={'read': 'Read access', 'write': 'Write access'},
)

async def get_token(
    token: Annotated[str, Depends(oauth2_scheme)],
) -> str:
    return token

AccessToken = Annotated[str, Depends(get_token, use_cache=True)]

async def require_oauth_scopes(security_scopes: SecurityScopes, token: AccessToken) -> None:
    pass

async def check_limit(token: AccessToken) -> None:
    pass

# The problem is here. If we remove the dependency from the router, the schema is generated correctly in both fastapi versions.
router = APIRouter(prefix='/v1', dependencies=[Depends(check_limit)])

channels_router = APIRouter(prefix='/channels', tags=['Channels'])
@channels_router.get("/", dependencies=[Security(require_oauth_scopes, scopes=['read'])])
def read_items():
    return {"msg": "You have READ access"}

router.include_router(channels_router)

app.include_router(router)
schema = app.openapi()
pretty_schema = json.dumps(schema, indent=4)
print(pretty_schema)

"""
with fastapi 0.123.7, the generated openapi schema icludes security without scopes:

                "security": [
                    {
                        "OAuth2AuthorizationCodeBearer": []
                    }
                ]

but in fastapi 0.121.3, the generated openapi schema includes two items in security:

                "security": [
                    {
                        "OAuth2AuthorizationCodeBearer": []
                    },
                    {
                        "OAuth2AuthorizationCodeBearer": [
                            "read"
                        ]
                    }
                ]
"""
```
---
Comment: That didn't fix it. 😱

Working on it now.
---
Comment: This was fixed by https://github.com/fastapi/fastapi/pull/14455, released in FastAPI 0.123.8 :tada:
---
Comment: This should be fixed now in https://github.com/fastapi/fastapi/pull/14459 (strike 2 ⚾). Released in FastAPI 0.123.9 🚀


# Issue #14465: Bug with async callable class dependency in fastapi>=0.123.6
Labels: bug
Creating the issue for completeness.

Solved by https://github.com/fastapi/fastapi/pull/14458

### Discussed in https://github.com/fastapi/fastapi/discussions/14452

Originally posted by **tanguyMichardiere** December  4, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.dependencies.models import Dependant
from uvicorn import run

class Dependency:
    def __init__(self):
        print("init")

    async def __call__(self):
        print("call")

print(Dependant(Dependency).is_coroutine_callable)
# `True` with fastapi>=0.123.6
# `False` with fastapi<0.123.6

app = FastAPI()

@app.get("/")
async def route(*, dependency: Annotated[Dependency, Depends()]):
    await dependency()

run(app)

# then `curl localhost:8000`
```

### Description

```
File ".venv/lib/python3.14/site-packages/fastapi/dependencies/utils.py", line 647, in solve_dependencies
    solved = await call(**solved_result.values)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Dependency' object can't be awaited
```

`fastapi.dependencies.models.Dependant` incorrectly identifies `Dependency` as a "coroutine callable", and `solve_dependencies` then tries to `await` an instance of `Dependency`.

### Operating System

macOS

### Operating System Details

_No response_

### FastAPI Version

0.123.7

### Pydantic Version

2.12.5

### Python Version

3.14.1

### Additional Context

_No response_

---
Comment: Fixed by https://github.com/fastapi/fastapi/pull/14458


# Issue #14466: Bug with async callable class dependency in fastapi>=0.123.6
Labels: bug
Creating this issue for completeness.

Solved by https://github.com/fastapi/fastapi/pull/14458

### Discussed in https://github.com/fastapi/fastapi/discussions/14452

Originally posted by **tanguyMichardiere** December  4, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.dependencies.models import Dependant
from uvicorn import run

class Dependency:
    def __init__(self):
        print("init")

    async def __call__(self):
        print("call")

print(Dependant(Dependency).is_coroutine_callable)
# `True` with fastapi>=0.123.6
# `False` with fastapi<0.123.6

app = FastAPI()

@app.get("/")
async def route(*, dependency: Annotated[Dependency, Depends()]):
    await dependency()

run(app)

# then `curl localhost:8000`
```

### Description

```
File ".venv/lib/python3.14/site-packages/fastapi/dependencies/utils.py", line 647, in solve_dependencies
    solved = await call(**solved_result.values)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Dependency' object can't be awaited
```

`fastapi.dependencies.models.Dependant` incorrectly identifies `Dependency` as a "coroutine callable", and `solve_dependencies` then tries to `await` an instance of `Dependency`.

### Operating System

macOS

### Operating System Details

_No response_

### FastAPI Version

0.123.7

### Pydantic Version

2.12.5

### Python Version

3.14.1

### Additional Context

_No response_

---
Comment: Fixed by https://github.com/fastapi/fastapi/pull/14458


# Issue #14467: Computed fields support breaks with mixed route types
Labels: bug
Creating issue for completeness.

Fixed by https://github.com/fastapi/fastapi/pull/14453

### Discussed in https://github.com/fastapi/fastapi/discussions/14451

Originally posted by **coltonevansid** December  4, 2025
### First Check

- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).

### Commit to Help

- [X] I commit to help with one of those options 👆

### Example Code

```python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from pydantic import BaseModel, computed_field

class ModelWithComputedField(BaseModel):
    name: str

    @computed_field
    @property
    def computed_name(self) -> str:
        return f"computed_{self.name}"

class SimpleModel(BaseModel):
      value: str

app = FastAPI()

@app.get("/with-computed")
def route_with_computed() -> ModelWithComputedField:
    """Route returning a model with computed fields."""
    return ModelWithComputedField(name="test")

@app.get("/without-computed")
def route_without_computed() -> SimpleModel:
    """Route returning a simple model (no computed fields)."""
    return SimpleModel(value="test")

if __name__ == "__main__":
    # This will raise KeyError when both routes are present
    schema = get_openapi(
        title="Test App",
        version="1.0.0",
        routes=app.routes,
        separate_input_output_schemas=False,  # Bug only occurs with False
    )
```

### Description

FastAPI 0.123.4 added support for computed fields in OpenAPI schemas (#13207) when `separate_input_output_schemas=False`, but the implementation has a bug where the schema generation crashes with a `KeyError` if the FastAPI app contains both:

1. Routes with response models that have computed fields
2. Routes with response models that don't have computed fields (e.g., dict responses or BaseModels without computed fields)

### Expected Behavior

  OpenAPI schema should generate successfully with computed fields included in models that have them, regardless of mixing route types.

### Current Behavior

  ```python
  File "../python3.13/site-packages/fastapi/_compat/v2.py", line 192, in get_schema_from_model_field
    json_schema = field_mapping[(field, override_mode or field.mode)]
                  ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: (ModelField(field_info=Fi
---
Comment: Fixed by https://github.com/fastapi/fastapi/pull/14453


# Issue #14483: Since FastAPI 0.119.0, using `arbitrary_types_allowed=True` with custom types that define their serialization and JSON Schema breaks when generating OpenAPI
Labels: bug
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

Using `arbitrary_types_allowed=True` with custom types that define their serialization and JSON Schema breaks when generating OpenAPI.

Originally reported in: https://github.com/fastapi/fastapi/discussions/14184

Extracting the minimal reproducible example from the comments:

```Python
from typing import Annotated

import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, WithJsonSchema, TypeAdapter

type MyNumpyArray = Annotated[
    np.ndarray, WithJsonSchema(TypeAdapter(list[float]).json_schema(), mode="serialization"),
]

class MyModel(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    custom_field: MyNumpyArray

app = FastAPI()

@app.get("/")
def test() -> MyModel:
    raise NotImplementedError()

print(app.openapi())
# {'openapi': '3.1.0', 'info': {'title': 'FastAPI', 'version': '0.1.0'}, 'paths': {'/': {'get': {'summary': 'Test', 'operationId': 'test__get', 'responses': {'200': {'description': 'Successful Response', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/MyModel'}}}}}}}}, 'components': {'schemas': {'MyModel': {'properties': {'custom_field': {'$ref': '#/components/schemas/MyNumpyArray'}}, 'type': 'object', 'required': ['custom_field'], 'title': 'MyModel'}, 'MyNumpyArray': {'items': {'type': 'number'}, 'type': 'array'}}}}
```

Should be solved by: https://github.com/fastapi/fastapi/pull/14482
---
Comment: It should be fixed in https://github.com/fastapi/fastapi/pull/14482, available in FastAPI 0.124.1, just released. :tada:


# Issue #14484: In FastAPI 0.123.7, annotations from code imported in `if TYPE_CHECKING` could break
Labels: bug
### Privileged issue

- [x] I'm @tiangolo or he asked me directly to create an issue here.

### Issue Content

In FastAPI 0.123.7, annotations from code imported in `if TYPE_CHECKING` could break

Originally discussed in https://github.com/fastapi/fastapi/discussions/14464 and https://github.com/fastapi/fastapi/pull/11355

Minimal example extracted from the discussion:

```Python
# /// script
# requires-python = "==3.14.*"
# dependencies = [
#   "fastapi==0.123.7",
#   "uvicorn",
# ]
# ///

from __future__ import annotations

from typing import TYPE_CHECKING, Annotated

from fastapi import Depends, FastAPI

if TYPE_CHECKING:
    from collections.abc import AsyncGenerator

app = FastAPI()

class DummyClient:
    async def get_people(self) -> list:
        return ["John Doe", "Jane Doe"]

    async def close(self) -> None: ...

async def get_client() -> AsyncGenerator[DummyClient, None]:
    client = DummyClient()
    yield client
    await client.close()

Client = Annotated[DummyClient, Depends(get_client)]

@app.get("/")
async def get_people(client: Client) -> list:
    return await client.get_people()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

Handled in https://github.com/fastapi/fastapi/pull/14485
---
Comment: This is fixed by https://github.com/fastapi/fastapi/pull/14485, available in FastAPI 0.124.2, just released. 🎉


# Issue #14493: Performance issue
Slow response under load


# Issue #14494: Performance issue
Slow response under load


# Issue #14496: Performance issue
Slow response under load
---
Comment: @LakshmiMandal, please, stop opening issue or you will be banned!


# Issue #14497: Performance issue
Slow response under load


# Issue #14498: Performance issue
Slow response under load


# Issue #14499: Performance issue
Slow response under load


# Issue #14500: Performance issue
Slow response under load