[Python] How to share a field between FastAPI body model and dependency without duplicating or...

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code:

    from fastapi import FastAPI, Depends, Body
    from pydantic import BaseModel
    import uvicorn

    app = FastAPI()

    class BS(BaseModel):
    x: str
    y: str

    def dep1(x: str = Body()):
    print(x)
    return x

    @app.post("/")
    def main(b: BS, d = Depends(dep1)) -> BS:
    print(b)
    print(d)
    return b

    uvicorn.run(app, host="0.0.0.0", port=8000)


    When I look at the JSON schema being generated it looks something like:

    {
    "b": {
    "x": "string"
    },
    "x": "string"
    }


    I want the dependency requiring x and the body of the endpoint requiring b.x to be the same and to both reuse the same x such that the JSON will look like

    {
    "x": "string"
    }


    I want to do this without accessing the raw Request object (because of a race condition in Starlette's stream() function. How do I do that?

    I don't want to use BS directly in the dependency because the dependency may be reused with different endpoints all accepting different models, that the only things common between them is the field x.

    I tried accepting the parameter in the dependency as body=Body(), but this just adds a field called body to the request.

    I am aware of Having a dependency through Depends() and a schema refer to the same root level key without ending up with multiple body parameters but I can't control the name the users of the dependency will give the the body in the endpoint itself, and it is too tricky to have them remember it and not introduce bugs by changing the name of the parameter of either the dependency or the endpoint without changing the other.

    Continue reading...

Compartilhe esta Página