How FastAPI manages WFT Forms?

Question:

I am migrating from Flask to FastAPI and it is not clear to me how FastAPI manages WTF Forms.

I would like to use forms in Classes. However, I don’t know if there is a correct way to do it in FastAPI, and if not what is the recommended solution to manage forms easily.

Here is a code example:

from fastapi import  Form

from wtforms import RadioField,SubmitField,SelectField, StringField,PasswordField, BooleanField

from wtforms.validators import Length, Email, InputRequired,EqualTo, DataRequired

class SignUpForm(Form):
    email = StringField('Email', validators=[DataRequired(), Length(1,100),Email()])
    
    password = ...
    confirm_password = ...

Is it possible to handle Forms in this way in FastAPI?

FastAPI has already a page explaining Forms in general, but I didn’t find any source explaining how to use it in a Class.

Any source to understand how FastAPI manages forms exactly is welcome.

Asked By: Nicolas-Fractal

||

Answers:

After some research, the best library to use WTF Forms with FastAPI is starlette-wtf.

See: https://pypi.org/project/WTForms/

Starlette-WTF integrates with Starlette and the FastAPI framework,
based on the features of Flask-WTF.

$ pip install starlette starlette-wtf jinja2 uvicorn 

Here is the code to do that:

from starlette_wtf import StarletteForm
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, EqualTo
from wtforms.widgets import PasswordInput


class CreateAccountForm(StarletteForm):
    email = TextField(
        'Email address',
        validators=[
            DataRequired('Please enter your email address'),
            Email()
        ]
    )

    password = PasswordField(
        'Password',
        widget=PasswordInput(hide_value=False),
        validators=[
            DataRequired('Please enter your password'),
            EqualTo('password_confirm', message='Passwords must match')
        ]
    )

    password_confirm = PasswordField(
        'Confirm Password',
        widget=PasswordInput(hide_value=False),
        validators=[
            DataRequired('Please confirm your password')
        ]
    )

Full code here.

Answered By: Nicolas-Fractal

you mentioned that:
"Starlette-WTF integrates with Starlette and the FastAPI framework, based on the features of Flask-WTF."

Can somebody show us how to use this library with fastapi? because in the code i see starlette only and nothing about fastapi.

Answered By: Przemek Nawrocki
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.