Skip to main content

No project description provided

Project description

Using pydantic-form-model with FastAPI: Advanced Features and Usage

The pydantic-form-model library allows you to define dynamic, structured forms using Pydantic models and serve them as JSON from a FastAPI backend. It supports various field types, including custom types, and provides built-in file handling capabilities. This guide explains how to use pydantic-form-model with FastAPI to define, serve, and handle forms, including advanced features like file handling, nested forms, and field properties.


Installation

Install the required dependencies using pip:

pip install pydantic-form-model

Key Features

1. Automatic Form Generation

With pydantic-form-model, you can define your forms using standard Pydantic classes and built-in Python types. The library automatically generates the form structure based on these definitions, eliminating the need for additional overhead.

For example:

from pydantic_form_model import FormModel, FField
from typing import Optional
from enum import StrEnum

class AvailableCountry(StrEnum):
    austria = 'Austria'
    belgium = 'Belgium'
    canada = 'Canada'

class Address(FormModel):
    country: AvailableCountry = FField(label='Country')
    zip_code: Optional[str] = FField(label='Zip Code', hint='e.g. 12345', default=None)
    street_name: str = FField(label='Street Name', style='width: 75%')
    street_number: Optional[str] = FField(label='Street Number', style='width: 25%')

class UserRegisterForm(FormModel):
    username: str = FField(label='Username', hint='Enter your username')
    password: str = FField(label='Password', hint='Enter your password')
    address: Address = FField(label='Address')
    terms_of_service_agreed: bool = FField(label='I agree to the terms and conditions')

The form structure is automatically generated based on the Pydantic model definitions, including validation rules, labels, hints, and more.


2. Arbitrarily Nested Forms

Forms can be nested arbitrarily, allowing you to create complex form structures. For example:

class PersonalInfo(FormModel):
    first_name: str = FField(label='First Name')
    last_name: str = FField(label='Last Name')

class UserProfile(FormModel):
    personal_info: PersonalInfo = FField(label='Personal Information')
    address: Address = FField(label='Address')

The UserProfile form will include the nested PersonalInfo and Address forms, and the JSON representation will reflect this structure.


3. File Handling

The library provides built-in support for file handling using the Base64File type. You can upload files as part of a form and process them using the save_files and load_file_data methods.

Saving Files

The save_files method allows you to save uploaded files to a specified directory.

@app.post("/upload-files")
def upload_files(form_data: UserRegisterForm = Depends()):
    form_data.save_files(directory="uploads")
    return {"message": "Files saved successfully"}

Loading Files

The load_file_data method allows you to load file data from a directory and populate the form with the file contents.

@app.get("/load-files")
def load_files():
    form = UserRegisterForm()
    form.load_file_data(directory="uploads")
    return form

4. FormField Properties

Each FormField in pydantic-form-model has several properties that define its behavior and appearance. These include:

  • field_type: The type of the field (e.g., text, number, boolean, file, etc.).
  • name: The name of the field.
  • label: A human-readable label for the field.
  • hint: A short description or hint for the field.
  • style: CSS styling for the field (e.g., width, height).
  • default: The default value for the field.
  • rendered: Whether the field is rendered by default.
  • validation_rules: A list of validation rules for the field (e.g., required, min_length, max_length).
  • choices: A list of predefined options for select fields.
  • item_properties: For object fields, this contains the nested fields.
  • item_definition: For list fields, this defines the structure of the list items.
  • meta: Additional metadata for the field.

Example of a FormField:

{
  "name": "username",
  "field_type": "text",
  "label": "Username",
  "hint": "Enter your username",
  "style": null,
  "default": null,
  "rendered": true,
  "validation_rules": [
    {
      "name": "required",
      "error_text": "Username is required."
    }
  ],
  "choices": null,
  "item_properties": null,
  "item_definition": null,
  "meta": {}
}

Example: Serving and Handling Forms

Here’s how you can serve and handle forms using pydantic-form-model and FastAPI:

from fastapi import FastAPI, Depends
from pydantic_form_model import FormModel, FField
from pydantic_form_model.form_fields import Base64File
from typing import Optional
from enum import StrEnum

app = FastAPI()

class AvailableCountry(StrEnum):
    austria = 'Austria'
    belgium = 'Belgium'
    canada = 'Canada'

class Address(FormModel):
    country: AvailableCountry = FField(label='Country')
    zip_code: Optional[str] = FField(label='Zip Code', hint='e.g. 12345', default=None)
    street_name: str = FField(label='Street Name', style='width: 75%')
    street_number: Optional[str] = FField(label='Street Number', style='width: 25%')

class UserRegisterForm(FormModel):
    username: str = FField(label='Username', hint='Enter your username')
    password: str = FField(label='Password', hint='Enter your password')
    address: Address = FField(label='Address')
    terms_of_service_agreed: bool = FField(label='I agree to the terms and conditions')
    some_file: list[Base64File] = FField(label='Upload Files')

@app.get("/form-definition", response_model=list[FormField])
def get_form_definition():
    form_fields: list[FormField] = UserRegisterForm.get_form_fields()
    return form_fields

@app.post("/submit-form")
def submit_form(form_data: UserRegisterForm = Depends()):
    form_data.save_files(directory="uploads")
    return {"message": f'Form submitted successfully and user {form_data.username} created.'}

With pydantic-form-model, you can easily define, serve, and handle forms in FastAPI, leveraging its powerful features like automatic form generation, nested forms, file handling, and customizable field properties. This makes it an excellent choice for building dynamic and structured form-based APIs.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_form_model-0.4.2.tar.gz (10.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_form_model-0.4.2-py3-none-any.whl (12.2 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_form_model-0.4.2.tar.gz.

File metadata

  • Download URL: pydantic_form_model-0.4.2.tar.gz
  • Upload date:
  • Size: 10.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.1 CPython/3.12.6 Windows/11

File hashes

Hashes for pydantic_form_model-0.4.2.tar.gz
Algorithm Hash digest
SHA256 ef1dc82b30186c15cc2c53fda02f36f61b6193a874571ef2a01f24f7df8bb170
MD5 ecd419f8685d49a7e9e77a201062f5c1
BLAKE2b-256 0602920edfa090ff56c3717b7d1e3ec833ce9f2ef7bfb08312cef3a89fba502c

See more details on using hashes here.

File details

Details for the file pydantic_form_model-0.4.2-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_form_model-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ffbe984b86d8d215452b50b5b9b0c39a6afcb981f9f659fa9ad4e8c643b72920
MD5 761525f89ddfc7de2f8c730e3a99ef35
BLAKE2b-256 a9b8abb4ed2beeefbacb9e5b491bac2c70b6076dea7a6fd67e00901ef2340192

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page