1

I have this small fastapi application

import uvicorn
from fastapi import FastAPI, Body, Query
from fastapi import Path

app = FastAPI()


@app.get("/test/{test_id}")
def test(
        id: str = Path(...),
        q: str = Query(...),
        b: str = Body(...)
):
    return "Hello world"


def main():
    uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)


if __name__ == "__main__":
    main()

it works as expected.


But I now make some changes as below

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

app = FastAPI()


class Input(BaseModel):
    id: str = Path(...)
    q: str = Query(...)
    b: str = Body(...)


@app.get("/test/{test_id}")
def test(inp: Input = Depends()):
    return "Hello world"


def main():
    uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)


if __name__ == "__main__":
    main()

I expect b to be shown as Body in the docs but it is being interpreted as a query string.

What is wrong?

Amin Ba
  • 1,603
  • 1
  • 13
  • 38

1 Answers1

0

A few things to be done to make the endpoint work

  1. Update b: str = Body(...) to b: str = Field(Body(...)).
  2. get request cannot have request body as input and will return an error. Use post request instead.
  3. The name of the path parameter should be consistent with the path /test/{test_id}, hence it should be test_id instead of id. Or else it will return a 422 Error: Unprocessable Entity.
import uvicorn
from fastapi import FastAPI, Depends, Body, Query
from fastapi import Path
from pydantic import BaseModel, Field

app = FastAPI()


class Input(BaseModel):
    test_id: str = Path(...)
    q: str = Query(...)
    b: str = Field(Body(...))


@app.post("/test/{test_id}")
def test(inp: Input = Depends()):
    return "Hello world"


def main():
    uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)


if __name__ == "__main__":
    main()
wavingtide
  • 1,032
  • 4
  • 19