2

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.

Nicolas-Fractal
  • 321
  • 1
  • 1
  • 9
  • 2
    Have you seen: https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi? – jhilmer Dec 29 '22 at 10:32
  • This is useful thanks, but maybe there is some clearer doc. The example you've mentioned seem a bit complex to me (maybe there is no choice). – Nicolas-Fractal Dec 29 '22 at 13:45

1 Answers1

3

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.

Nicolas-Fractal
  • 321
  • 1
  • 1
  • 9