2

I have the below route defined in FastAPI:

from schema import DocumentRequest

responses = {
    404: {"description": "The shipment was not found"},
}
@router.get("/{id}", responses=responses)
def get_documents(documents: DocumentRequest = Form(...)):   
    #Removed code in the example... 
    return

And my DocumentRequest.py schema looks like:

from pydantic import BaseModel

class DocumentRequest(BaseModel):
    shipment_id: str
    company: str
    enterprise_id: str
    server_id: str
    data_target_type: str

The problem is that this gives me the following in the docs:

enter image description here

As you can see in the above screenshot, the form data is having a parent declared called "documents", and the request itself is defined under this "documents".

How can I declare that it is only the form fields declared in the schema DocumentRequest.py that needs to be passed?

I can fix it by manually entereing the form fields like so:

def get_documents(shipment_id: str = Form(default=None), company: str = Form(default=None), enterprise_id = Form(default=None), server_id: str = Form(default=None), data_target_type: str = Form(default=None)):

But I would like to use the schema defined.

oliverbj
  • 5,771
  • 27
  • 83
  • 178
  • 2
    Generally it's not automagically supported in the way you want to achieve it, but there's a workaround. Generally the Pydantic matching is made for mapping to JSON bodies. [How to use a Pydantic model with Form data in FastAPI](https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi) – MatsLindh Aug 12 '22 at 08:48
  • 1
    (1) You shouldn't be using a `GET` request when sending request `body`, but rather use a `POST` request, (2) You can't declare a Pydantic model and expect it to receive `form-data`, because of using `Form()`, (3) For alternative solutions see the post provided by @MatsLindh above, as well as [here](https://stackoverflow.com/a/70640522/17865804) and [here](https://stackoverflow.com/a/71439821/17865804), in case you need to use Pydantic models and Form/File data together. – Chris Aug 12 '22 at 08:55

0 Answers0