Skip to main content

FastAPI Validation

FastAPI Validation support both SQLAlchemy for sql database and BeanieODM for nosql Database. To use the @Exists and @Unique decorator we need to set global-variable for the database_type Check the sample code below

For SQL Database using SQLAlchemy as ORM

from fastapi_validation import DatabaseTypeEnum

engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=False, pool_size=50, max_overflow=100)
global_db_session: Session = sessionmaker(
    autoflush=False, autobegin=True, bind=engine, join_transaction_mode='rollback_only'
)()
def run_with_global_session(callback):
    try:
        return callback(global_db_session)
    except Exception as e:
        global_db_session.rollback()
        raise e

GlobalVariable.set('run_with_global_session', run_with_global_session)
GlobalVariable.set('database_type', DatabaseTypeEnum.SQL)

For Nosql Database using Beanie as ODM

GlobalVariable.set('database_type', DatabaseTypeEnum.NOSQL) # We can skip this line because the defautl database_type is No-SQL

How to use

Exists decorator

from fastapi_validation import FieldValidator, Exists

class UpdateProfileDto(BaseDto):
  avatar_id: UUID | None = None

  _exist_avatar = FieldValidator('avatar_id')(
    Exists(
      table=MediaEntity,
      column='id',
      customs=[{'column': 'type', 'value': MediaType.IMAGE}],
    )
  )

Unique decorator

class InviteUserDto(BaseDto):
  username: str = Field(max_length=255, min_length=1)

  _unique_username = FieldValidator('username')(
    Unique(table=UserEntity, column='username', customs=[{'column': 'deleted_at', 'value': None}])
  )

Customized FieldValidator handler

from fastapi_validation import FieldValidator

class InviteUserDto(BaseDto):
  username: str = Field(max_length=255, min_length=1)

  _validate_username = FieldValidator('username')(validate_username)

def validate_username(username: str | None = None) -> str:
  if not username:
    return username

  if not re.search(USERNAME_REGEX, username):
    raise ValueError('invalid username')

  return username

ModelValidator

from fastapi_validation import ModelValidator

def required_phone_number_and_code_pair(cls, values):
  phone_code, phone_number = values.phone_code, values.phone_number

  is_missing_only_phone_number = phone_code is not None and phone_number is None
  is_missing_only_phone_code = phone_number is not None and phone_code is None

  if is_missing_only_phone_number or is_missing_only_phone_code:
    throw_validation_with_exception(MissingPhoneNumberPhoneCodeError(loc=('body', 'phone_code', 'phone_number')))

  return values

class CheckPhoneTokenDto(BaseDto):
  phone_code: CodeValidation
  phone_number: PhoneNumberValidation
  token: int = Field(ge=100000, le=999999)

  _phone_number_and_code_validation = ModelValidator()(required_phone_number_and_code_pair)

list_int_enum_query_param

from fastapi_validation import SortParam, Sorts, 
from fastapi_validation import list_int_enum_query_param

class RoleEnum(int, Enum):
  ADMIN = 1
  ADMIN_ASSISTANT = 2

@controller('users')
@tag('Users')
@auth()
class UserController:
  def __init__(
    self, user_service: UserService = Depends()
  ):
    self.user_service = user_service

  @get()
  @response(UserResponse)
  async def list_users_by_role(
    self,
    roles: list[int] = list_int_enum_query_param(values=RoleEnum, key='roles'),
  ):
    return await self.user_service.list_users_by_role(roles)

PasswordValidation

from fastapi_validation import PasswordValidation

class ChangePasswordDto(BaseDto):
  old_password: PasswordValidation
  new_password: PasswordValidation

Metadata

Release files for fastapi-validation 1.1.19

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-validation 1.1.19
File Size Uploaded
fastapi_validation-1.1.19.tar.gz 12.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-validation 1.1.19
File Interpreter ABI Platform
fastapi_validation-1.1.19-py3-none-any.whl Python 3 none any Details

Total release size: 24.2 kB

Release files / fastapi_validation-1.1.19.tar.gz

Download URL fastapi_validation-1.1.19.tar.gz
Size 12.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e57e40fadebe004d9f77658aef9b718ddf47e27c94caf0dcea65fc1aa3e9ac4d
BLAKE2b-256 checksum
How to use checksums
cd0e0960de1d1ec21342cc8d1633ae5f763a4d093a5f012773a97ef3c1ca9d63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.10.14

Release files / fastapi_validation-1.1.19-py3-none-any.whl

Download URL fastapi_validation-1.1.19-py3-none-any.whl
Size 12.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7ddc021465bef3b0e040e0637bc6c6d03bd7ded0f55e71d2f725d25918f36962
BLAKE2b-256 checksum
How to use checksums
92c0ed7e7bc334230d35ca99335a13a9fdf66f6333a327d9431107a76402e8de
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.10.14

Release history Release notifications | RSS feed

This release

1.1.19 This release

2 release files

1.1.15

2 release files

1.1.14

2 release files

1.1.13

2 release files

1.1.12

2 release files

1.1.11

2 release files

1.1.10

2 release files

1.1.9

2 release files

1.1.8

2 release files

1.1.7

2 release files

1.1.6

2 release files

1.1.5

2 release files

1.1.4

2 release files

1.1.3

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page