3

So I have a simple fastapi model as follows:

 from typing import List
 
 from fastapi import Query, Depends, FastAPI
 from pydantic import BaseModel
 
 class QueryParams(BaseModel):
     req1: float = Query(...)
     opt1: int = Query(None)
     req_list: List[str] = Query(...)
 
 
 app = FastAPI()
 @app.post("/test", response_model=QueryParams)
 def foo(q: QueryParams = Depends()):
     return q

which works with the following command: curl -X "POST" "http://localhost:8000/test?req1=1" -d '{["foo"]}'

However! I need it to work additionally with allowing the params in the uri request as such: curl -X "POST" "http://localhost:8000/test?req1=1&req_list=foo"

I know that if I took out the req_list from the BaseModel, and shoved it in the function header as such

 from typing import List
 
 from fastapi import Query, Depends, FastAPI
 from pydantic import BaseModel
 
 class QueryParams(BaseModel):
     req1: float = Query(...)
     opt1: int = Query(None)
 
 
 app = FastAPI()
 @app.post("/test", response_model=QueryParams)
 def foo(q: QueryParams = Depends(), req_list: List[str] = Query(...)):
     return q

that it would work, but is there any way to keep it in the basemodel?

0

1 Answer 1

4

Well I figured it out:

 from typing import List
 
 from fastapi import Query, Depends, FastAPI
 from pydantic.dataclasses import dataclass
 
 @dataclass
 class QueryParams:
     req1: float = Query(...)
     opt1: int = Query(None)
     req_list: List[str] = Query(...)
 
 
 app = FastAPI()
 @app.post("/test", response_model=QueryParams)
 def foo(q: QueryParams = Depends()):
     return q
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.