3
votes

I'm new to FastAPI (migrating from Flask) and I'm trying to create a Pydantic Model to my GET route

from fastapi import APIRouter,Depends
from pydantic import BaseModel
from typing import Optional,List

router = APIRouter()

class SortModel(BaseModel):
    field:    Optional[str]
    directions: List[str]

@router.get("/pydanticmodel")
def get_sort(criteria: SortModel = Depends(SortModel)):
    pass #my code for handling this route.....

When I'm running curl -X GET http://localhost:XXXX/pydanticmodel?directions=up&directions=asc&field=id I'm getting 422 Unprocessable Entity: {"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]}

But if I'm changing directions:List[str] -> directions: str I'm getting 200 OK with directions="asc". What is the reason that str works for query param and List[str] does not? what am I doing wrong?

Thanks.

2

2 Answers

0
votes

I'm running into the same issue. The following solution will work, but it isn't really what I want however maybe it's good enough for you:

from fastapi import APIRouter,Depends, Query
from pydantic import BaseModel
from typing import Optional,List

router = APIRouter()

class SortModel(BaseModel):
    field:    Optional[str]

@router.get("/pydanticmodel")
def get_sort(criteria: SortModel = Depends(SortModel), directions: List[str] = Query(...)):
    pass #my code for handling this route.....
-1
votes

It's not a Pydantic or FastAPI problem.

If you want to send an array with curl you should use -d flag.

In: curl -X GET "http://127.0.0.1:8000/pydanticmodel?field=123"  -d "[\"string\"]"
Out: {"field":"123","directions":["string"]}

Now your code should work perfectly.