How to get multiple form input field as dictionary in fastapi?

Viewed 2327

I have to submit a form like this to fastapi endpoint with 14 input fields, like bellow

<FORM NAME='TESTFORM' ACTION='URL' METHOD='POST'>
            <input type='hidden' name='CURRENCY' value='PAYMENT_CURRENCY'>
            <input type='hidden' name='GATEWAYNAME' value='GATEWAY_USED'>
            <input type='hidden' name='RESPMSG' value='RESPONSE_MESSAGE_DESCRIPTION'>
            <input type='hidden' name='BANKNAME' value='BANK_NAME_OF_ISSUING_PAYMENT_MODE'>
</FORM>

I can get fields one by one like bellow.

@app.post("/users/payment/response")
def payment_response_users(
        response_currency:str = Form(...), response_gateway:str = Form(...))

same way for all 14 fields.

but is there a way to get all the fields via a single pydantic schema. like bellow

@app.post("/users/payment/response")
def payment_response_users(
        response_model:PaymentRespModel = Form(...))
1 Answers

Create a class model with all your fields and just add yor class

    from pydantic import BaseModel        

    class FormData(BaseModel):
        response_currency: str
        response_gateway: str
        # your all fields

    
    def payment_response_users(form_data: FormData):
        
        # your code , access using form_data.response_currency and so on...
Related