fastapi-validation-schemes


"/home/yossef/notes/full-stack/python-backend/fastapi/fastapi-validation-schemes.md"

path: full-stack/python-backend/fastapi/fastapi-validation-schemes.md

- **fileName**: fastapi-validation-schemes
- **Created on**: 2025-03-15 00:11:14

starting vaildation and schemes for fastapi

from enum import IntEnum # allowing create a num type
from typing import List, Optional, # using for list and Optional values
from fastapi import Body, FastAPI, # request body and fastapi
from pydantic import BaseModel, Field,
"""
- BaseModel class for create a scheme for fastapi  A base class for 
    creating Pydantic models.
- Field specifiy default value and unique or require or length and adding 
    description for attriubte
"""

for more information about fields

fields

creating some examples for validation schemes

## starting create the scheme for the todo
# enum byte of INT values
class Priority(IntEnum):
    LOW = 3
    MEDIUM =  2
    HIGH = 1

class TodoBase(BaseModel):
    todo_name: str = Field(..., min_length=3, max_length=300, description=
                           "todo name")
    todo_description: str = Field(..., min_length=3, max_length=300, description=
                           "description for todo")
    priority: Priority = Field(default=Priority.LOW, description=
                               "priority for todo")

# Optional for set optional for the attruibute
class TodoUpdate(BaseModel):
    todo_name: Optional[str] = None
    todo_description: Optional[str] = None
    priority: Optional[Priority] = None

class TodoCreate(TodoBase):
    pass

class Todo(TodoBase):
    todo_id: int = Field(..., description="the indentifer id for todo")

creating a list of todos

todo_user = [
    Todo(todo_id=1, todo_name="eating", 
         todo_description="learning new cooking recipe", priority=Priority.LOW),
    Todo(todo_id=2, todo_name="code", todo_description="code for 1 hour",
         priority=Priority.HIGH),
    Todo(todo_id=3, todo_name="mediate", todo_description="mediate for 20 min", 
         priority=Priority.MEDIUM),
    Todo(todo_id=4, todo_name="sleep", todo_description="sleep at 10 am", 
         priority=Priority.MEDIUM)
]

now creating a endpoint and apply the todo changes type

# response_model specifi the response for endpoint
@api.post('/todo/', response_model=Todo)
def add_todo(todo: TodoCreate = Body(...)):
    """
    Parameters
    ---
    todo : dict
        the new todo that gone adding to the list of todos
    
    Returns
    ---
    dict
        a dict for the new todo that gone adding to the list of todos
    """
    # get the max id from todo
    new_todo_id = max(todo.todo_id for todo in todo_user) + 1

    # create a new todo
    new_todo = Todo(
        todo_id= new_todo_id,
        todo_name= todo.todo_name,
        todo_description= todo.todo_description
    )

    # append id to todo
    todo_user.append(new_todo)

    # return todo
    return new_todo

for information about handle Exception and error

./http-exception.md

before: ./startup-fastapi.md
continue: ./http-exception.md