This is a fantastic architecture! Your choice of Next.js, TypeScript, ZOD, Zustand on the frontend, and FastAPI, Pydantic, SQLAlchemy, PostgreSQL on the backend, with JSONB for form definitions, is very solid and modern.
Let's break down the module generation, suggest improvements, and highlight potential weaknesses.
High-Level Architecture Overview
graph TD
A[Next.js Frontend] -->|Builds & Saves Form Definition (JSON)| B(FastAPI Backend)
B -->|Stores Form Definition (JSONB)| C(PostgreSQL Database)
B -->|Validates Data (Pydantic)| C
A -->|Fetches Form Definition| B
A -->|Submits Form Data| B
B -->|Stores Form Data (JSONB)| C
subgraph Frontend
A1[Form Builder Page]
A2[Field Palette]
A3[Form Canvas (Drag & Drop)]
A4[Field Configurator]
A5[Dynamic Form Renderer]
A6[Zustand Store]
A7[ZOD Validation]
A8[Typescript Interfaces]
end
subgraph Backend
B1[FastAPI Endpoints]
B2[Pydantic Models]
B3[SQLAlchemy ORM]
B4[PostgreSQL JSONB]
end
A1 -- Uses --> A2
A1 -- Uses --> A3
A3 -- Shows --> A4
A1 -- Manages State --> A6
A5 -- Renders from --> A1
A5 -- Validates with --> A7
A6 -- Defines with --> A8
A -- Makes API Calls --> B1
B1 -- Validates with --> B2
B1 -- Interacts with DB via --> B3
B3 -- Stores Data in --> B4
1. Frontend Module (Next.js, TypeScript, ZOD, Zustand)
A. Data Modeling (TypeScript Interfaces)
Define the structure of your form fields and the form itself.
// types/formBuilder.ts
export enum FieldType {
Text = 'text',
Number = 'number',
Boolean = 'boolean', // Checkbox for simple boolean, or a toggle
File = 'file',
Select = 'select', // Dropdown
Radio = 'radio',
CheckboxGroup = 'checkboxGroup', // For multiple checkboxes with same name
}
export interface FormOption {
label: string;
value: string | number | boolean;
}
// Base interface for all form fields
export interface BaseFormField {
id: string; // Unique ID for the field within the form
type: FieldType;
label: string;
required: boolean;
placeholder?: string;
defaultValue?: string | number | boolean | FileList | null;
description?: string;
}
// Specific field interfaces
export interface TextField extends BaseFormField {
type: FieldType.Text;
minLength?: number;
maxLength?: number;
}
export interface NumberField extends BaseFormField {
type: FieldType.Number;
min?: number;
max?: number;
}
export interface BooleanField extends BaseFormField {
type: FieldType.Boolean;
}
export interface FileField extends BaseFormField {
type: FieldType.File;
accept?: string; // e.g., "image/*, .pdf"
multiple?: boolean;
}
export interface SelectField extends BaseFormField {
type: FieldType.Select;
options: FormOption[];
}
export interface RadioField extends BaseFormField {
type: FieldType.Radio;
options: FormOption[];
}
export interface CheckboxGroupField extends BaseFormField {
type: FieldType.CheckboxGroup;
options: FormOption[];
// For checkbox groups, defaultValue might be an array of selected values
defaultValue?: (string | number | boolean)[];
}
// Union type for all possible form fields
export type FormField =
| TextField
| NumberField
| BooleanField
| FileField
| SelectField
| RadioField
| CheckboxGroupField;
// Main Form Definition Interface
export interface FormDefinition {
id: string; // Unique ID for the form itself
title: string;
description?: string;
fields: FormField[];
createdAt?: string;
updatedAt?: string;
}
// Interface for submitted data
export interface FormSubmissionData {
[fieldId: string]: string | number | boolean | string[] | FileList | null;
}
export interface FormSubmission {
id: string;
formId: string;
data: FormSubmissionData;
submittedAt: string;
}
B. Global State Management (Zustand)
Manages the form definition being built and available field types.
// store/formBuilderStore.ts
import { create } from 'zustand';
import { FormDefinition, FormField, FieldType } from '../types/formBuilder';
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
interface FormBuilderState {
currentForm: FormDefinition;
availableFieldTypes: FieldType[];
addField: (type: FieldType) => void;
updateField: (fieldId: string, updates: Partial<FormField>) => void;
removeField: (fieldId: string) => void;
reorderFields: (startIndex: number, endIndex: number) => void;
setFormDefinition: (form: FormDefinition) => void;
resetForm: () => void;
setTitle: (title: string) => void;
setDescription: (description: string) => void;
}
const initialFormState: FormDefinition = {
id: uuidv4(),
title: 'New Form',
description: '',
fields: [],
};
export const useFormBuilderStore = create<FormBuilderState>((set, get) => ({
currentForm: initialFormState,
availableFieldTypes: [
FieldType.Text,
FieldType.Number,
FieldType.Boolean,
FieldType.File,
FieldType.Select,
FieldType.Radio,
FieldType.CheckboxGroup,
],
addField: (type) => {
const newField: FormField = {
id: uuidv4(),
type: type,
label: `New ${type.charAt(0).toUpperCase() + type.slice(1)} Field`,
required: false,
// Add type-specific defaults as needed
...(type === FieldType.Select || type === FieldType.Radio || type === FieldType.CheckboxGroup
? { options: [{ label: 'Option 1', value: 'option1' }] }
: {}),
...(type === FieldType.File ? { accept: '', multiple: false } : {}),
} as FormField; // Type assertion as newField might not perfectly match initial type
set((state) => ({
currentForm: {
...state.currentForm,
fields: [...state.currentForm.fields, newField],
},
}));
},
updateField: (fieldId, updates) => {
set((state) => ({
currentForm: {
...state.currentForm,
fields: state.currentForm.fields.map((field) =>
field.id === fieldId ? { ...field, ...updates } : field
),
},
}));
},
removeField: (fieldId) => {
set((state) => ({
currentForm: {
...state.currentForm,
fields: state.currentForm.fields.filter((field) => field.id !== fieldId),
},
}));
},
reorderFields: (startIndex, endIndex) => {
set((state) => {
const result = Array.from(state.currentForm.fields);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return {
currentForm: {
...state.currentForm,
fields: result,
},
};
});
},
setFormDefinition: (form) => set({ currentForm: form }),
resetForm: () => set({ currentForm: initialFormState }),
setTitle: (title: string) => {
set((state) => ({
currentForm: {
...state.currentForm,
title: title,
},
}));
},
setDescription: (description: string) => {
set((state) => ({
currentForm: {
...state.currentForm,
description: description,
},
}));
},
}));
C. ZOD for Dynamic Form Validation
This utility function will dynamically create a ZOD schema based on your FormDefinition.
// utils/zodSchemaGenerator.ts
import { z } from 'zod';
import { FormDefinition, FormField, FieldType } from '../types/formBuilder';
export const buildZodSchema = (formDefinition: FormDefinition) => {
const schemaFields: { [key: string]: z.ZodTypeAny } = {};
formDefinition.fields.forEach((field) => {
let fieldSchema: z.ZodTypeAny;
switch (field.type) {
case FieldType.Text:
fieldSchema = z.string();
if ('minLength' in field && field.minLength) fieldSchema = fieldSchema.min(field.minLength);
if ('maxLength' in field && field.maxLength) fieldSchema = fieldSchema.max(field.maxLength);
break;
case FieldType.Number:
fieldSchema = z.number().transform((val) => (val === '' ? null : Number(val))); // Handle empty string from input
if ('min' in field && field.min !== undefined) fieldSchema = fieldSchema.min(field.min);
if ('max' in field && field.max !== undefined) fieldSchema = fieldSchema.max(field.max);
break;
case FieldType.Boolean:
fieldSchema = z.boolean();
break;
case FieldType.File:
// For file uploads, Zod's `instanceof FileList` is generally used.
// On submission, you'll likely send files via FormData, not JSON.
// For simple validation, you might check if it's an array for multiple files or single file object.
// Actual file type/size validation often happens on the backend.
fieldSchema = z.any(); // More complex validation logic might be needed here or on backend.
break;
case FieldType.Select:
case FieldType.Radio:
if ('options' in field) {
const allowedValues = field.options.map((opt) => opt.value);
fieldSchema = z.union([
z.string().refine((val) => allowedValues.includes(val), { message: 'Invalid option selected' }),
z.number().refine((val) => allowedValues.includes(val), { message: 'Invalid option selected' }),
z.boolean().refine((val) => allowedValues.includes(val), { message: 'Invalid option selected' }),
]);
} else {
fieldSchema = z.string(); // Fallback
}
break;
case FieldType.CheckboxGroup:
if ('options' in field) {
const allowedValues = field.options.map((opt) => opt.value);
fieldSchema = z.array(
z.union([
z.string().refine((val) => allowedValues.includes(val), { message: 'Invalid option selected' }),
z.number().refine((val) => allowedValues.includes(val), { message: 'Invalid option selected' }),
z.boolean().refine((val) => allowedValues.includes(val), { message: 'Invalid option selected' }),
])
);
} else {
fieldSchema = z.array(z.string()); // Fallback
}
break;
default:
fieldSchema = z.any();
}
if (field.required) {
fieldSchema = fieldSchema.nonempty('This field is required'); // For strings, arrays
fieldSchema = fieldSchema.or(z.null()).or(z.undefined()); // Allow null/undefined initially, then check non-empty
fieldSchema = fieldSchema.refine(
(val) => {
if (val === null || val === undefined) return false;
if (typeof val === 'string' && val.trim() === '') return false;
if (Array.isArray(val) && val.length === 0) return false;
// Add more checks for specific types if needed
return true;
},
{ message: 'This field is required.' }
);
} else {
fieldSchema = fieldSchema.nullable().optional(); // Make it optional if not required
}
schemaFields[field.id] = fieldSchema;
});
return z.object(schemaFields);
};
D. API Integration (Example using fetch or axios)
// lib/api.ts
import { FormDefinition, FormSubmission } from '../types/formBuilder';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000';
export const formApi = {
// --- Form Definitions ---
createForm: async (form: FormDefinition): Promise<FormDefinition> => {
const response = await fetch(`${API_BASE_URL}/forms`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
if (!response.ok) throw new Error('Failed to create form');
return response.json();
},
getForm: async (id: string): Promise<FormDefinition> => {
const response = await fetch(`${API_BASE_URL}/forms/${id}`);
if (!response.ok) throw new Error('Failed to fetch form');
return response.json();
},
updateForm: async (id: string, form: Partial<FormDefinition>): Promise<FormDefinition> => {
const response = await fetch(`${API_BASE_URL}/forms/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
if (!response.ok) throw new Error('Failed to update form');
return response.json();
},
deleteForm: async (id: string): Promise<void> => {
const response = await fetch(`${API_BASE_URL}/forms/${id}`, {
method: 'DELETE',
});
if (!response.ok) throw new Error('Failed to delete form');
},
getAllForms: async (): Promise<FormDefinition[]> => {
const response = await fetch(`${API_BASE_URL}/forms`);
if (!response.ok) throw new Error('Failed to fetch forms');
return response.json();
},
// --- Form Submissions ---
submitFormData: async (formId: string, data: FormData): Promise<FormSubmission> => {
// Note: For file uploads, use FormData, not JSON.stringify
const response = await fetch(`${API_BASE_URL}/forms/${formId}/submit`, {
method: 'POST',
body: data, // FormData handles Content-Type automatically
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to submit form data');
}
return response.json();
},
getFormSubmissions: async (formId: string): Promise<FormSubmission[]> => {
const response = await fetch(`${API_BASE_URL}/forms/${formId}/submissions`);
if (!response.ok) throw new Error('Failed to fetch submissions');
return response.json();
},
};
E. Components (Conceptual structure)
You'll likely use react-beautiful-dnd for the drag-and-drop functionality.
# Install react-beautiful-dnd
npm install react-beautiful-dnd # or yarn add
npm install --save-dev @types/react-beautiful-dnd # for TypeScript
components/form-builder/FieldPalette.tsx
// components/form-builder/FieldPalette.tsx
import React from 'react';
import { FieldType } from '../../types/formBuilder';
import { Draggable } from 'react-beautiful-dnd';
interface FieldPaletteProps {
availableFieldTypes: FieldType[];
}
export const FieldPalette: React.FC<FieldPaletteProps> = ({ availableFieldTypes }) => {
return (
<div className="p-4 border-r bg-gray-50 h-full overflow-y-auto">
<h3 className="text-lg font-semibold mb-4">Field Types</h3>
{availableFieldTypes.map((type, index) => (
<Draggable key={type} draggableId={type} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className="p-3 mb-2 bg-white border rounded shadow-sm hover:bg-gray-100 cursor-grab text-sm"
>
{type.charAt(0).toUpperCase() + type.slice(1)}
</div>
)}
</Draggable>
))}
</div>
);
};
components/form-builder/FormCanvas.tsx
// components/form-builder/FormCanvas.tsx
import React from 'react';
import { FormField } from '../../types/formBuilder';
import { Droppable, Draggable } from 'react-beautiful-dnd';
import { FormFieldEditor } from './FormFieldEditor'; // Component to edit a field's properties
interface FormCanvasProps {
fields: FormField[];
onFieldSelect: (fieldId: string) => void;
onRemoveField: (fieldId: string) => void;
selectedFieldId: string | null;
}
export const FormCanvas: React.FC<FormCanvasProps> = ({
fields,
onFieldSelect,
onRemoveField,
selectedFieldId,
}) => {
return (
<Droppable droppableId="form-canvas">
{(provided) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
className="p-6 bg-white border rounded shadow-md h-full overflow-y-auto min-h-[300px]"
>
{fields.length === 0 && (
<p className="text-gray-500 text-center py-10">Drag fields here to build your form</p>
)}
{fields.map((field, index) => (
<Draggable key={field.id} draggableId={field.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className={`p-4 mb-3 border rounded bg-gray-50 relative group
${selectedFieldId === field.id ? 'border-blue-500 ring-2 ring-blue-200' : 'border-gray-200'}
hover:border-blue-300 transition-colors duration-200`}
onClick={() => onFieldSelect(field.id)}
>
<span className="font-medium text-gray-700">{field.label} ({field.type})</span>
{field.required && <span className="text-red-500 text-xs ml-1">*</span>}
<button
onClick={(e) => { e.stopPropagation(); onRemoveField(field.id); }}
className="absolute top-2 right-2 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
title="Remove Field"
>
×
</button>
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
);
};
components/form-builder/FormFieldConfigurator.tsx
This component renders based on the selectedFieldId from the state and allows editing.
// components/form-builder/FormFieldConfigurator.tsx
import React, { useState, useEffect } from 'react';
import { FormField, FieldType, FormOption } from '../../types/formBuilder';
import { useFormBuilderStore } from '../../store/formBuilderStore';
interface FormFieldConfiguratorProps {
field: FormField;
onClose: () => void;
}
export const FormFieldConfigurator: React.FC<FormFieldConfiguratorProps> = ({ field, onClose }) => {
const updateField = useFormBuilderStore((state) => state.updateField);
const [currentField, setCurrentField] = useState<FormField>(field);
useEffect(() => {
setCurrentField(field); // Sync internal state when prop changes
}, [field]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
const { name, value, type, checked } = e.target as HTMLInputElement;
setCurrentField((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
};
const handleOptionChange = (index: number, type: 'label' | 'value', val: string) => {
if (
currentField.type === FieldType.Select ||
currentField.type === FieldType.Radio ||
currentField.type === FieldType.CheckboxGroup
) {
const newOptions = [...currentField.options];
newOptions[index] = { ...newOptions[index], [type]: val };
setCurrentField((prev) => ({ ...prev, options: newOptions }) as FormField);
}
};
const addOption = () => {
if (
currentField.type === FieldType.Select ||
currentField.type === FieldType.Radio ||
currentField.type === FieldType.CheckboxGroup
) {
setCurrentField((prev) => ({
...prev,
options: [...prev.options, { label: `Option ${prev.options.length + 1}`, value: `option${prev.options.length + 1}` }],
}) as FormField);
}
};
const removeOption = (index: number) => {
if (
currentField.type === FieldType.Select ||
currentField.type === FieldType.Radio ||
currentField.type === FieldType.CheckboxGroup
) {
const newOptions = currentField.options.filter((_, i) => i !== index);
setCurrentField((prev) => ({ ...prev, options: newOptions }) as FormField);
}
};
const handleSave = () => {
updateField(currentField.id, currentField);
onClose();
};
if (!field) return null;
return (
<div className="p-4 border-l bg-gray-50 h-full overflow-y-auto">
<h3 className="text-lg font-semibold mb-4">Edit Field: {field.label}</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700">Label</label>
<input
type="text"
name="label"
value={currentField.label}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
<div>
<label className="inline-flex items-center">
<input
type="checkbox"
name="required"
checked={currentField.required}
onChange={handleChange}
className="form-checkbox"
/>
<span className="ml-2 text-sm text-gray-700">Required</span>
</label>
</div>
{/* Common properties */}
{('placeholder' in currentField) && (
<div>
<label className="block text-sm font-medium text-gray-700">Placeholder</label>
<input
type="text"
name="placeholder"
value={currentField.placeholder || ''}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
)}
{/* Type-specific properties */}
{currentField.type === FieldType.Text && (
<>
<div>
<label className="block text-sm font-medium text-gray-700">Min Length</label>
<input
type="number"
name="minLength"
value={(currentField as FormField & { minLength?: number }).minLength || ''}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Max Length</label>
<input
type="number"
name="maxLength"
value={(currentField as FormField & { maxLength?: number }).maxLength || ''}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
</>
)}
{currentField.type === FieldType.Number && (
<>
<div>
<label className="block text-sm font-medium text-gray-700">Min Value</label>
<input
type="number"
name="min"
value={(currentField as FormField & { min?: number }).min || ''}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Max Value</label>
<input
type="number"
name="max"
value={(currentField as FormField & { max?: number }).max || ''}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
</>
)}
{(currentField.type === FieldType.Select ||
currentField.type === FieldType.Radio ||
currentField.type === FieldType.CheckboxGroup) && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Options</label>
{(currentField as FormField & { options: FormOption[] }).options.map((option, index) => (
<div key={index} className="flex items-center mb-2 space-x-2">
<input
type="text"
value={option.label}
onChange={(e) => handleOptionChange(index, 'label', e.target.value)}
placeholder="Label"
className="flex-1 border border-gray-300 rounded-md shadow-sm p-2 text-sm"
/>
<input
type="text"
value={String(option.value)}
onChange={(e) => handleOptionChange(index, 'value', e.target.value)}
placeholder="Value"
className="flex-1 border border-gray-300 rounded-md shadow-sm p-2 text-sm"
/>
<button
onClick={() => removeOption(index)}
className="text-red-500 hover:text-red-700 text-lg px-2 py-1"
>
×
</button>
</div>
))}
<button
onClick={addOption}
className="mt-2 px-3 py-1 bg-blue-500 text-white rounded-md text-sm hover:bg-blue-600"
>
Add Option
</button>
</div>
)}
{currentField.type === FieldType.File && (
<>
<div>
<label className="block text-sm font-medium text-gray-700">Accepted File Types (e.g., .pdf, image/*)</label>
<input
type="text"
name="accept"
value={(currentField as FormField & { accept?: string }).accept || ''}
onChange={handleChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2"
/>
</div>
<div>
<label className="inline-flex items-center">
<input
type="checkbox"
name="multiple"
checked={(currentField as FormField & { multiple?: boolean }).multiple || false}
onChange={handleChange}
className="form-checkbox"
/>
<span className="ml-2 text-sm text-gray-700">Allow Multiple Files</span>
</label>
</div>
</>
)}
<div className="flex justify-end space-x-2 mt-6">
<button
onClick={onClose}
className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleSave}
className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"
>
Save Changes
</button>
</div>
</div>
</div>
);
};
pages/form-builder.tsx (Main Page)
// pages/form-builder.tsx
import React, { useState, useEffect } from 'react';
import { DragDropContext, DropResult } from 'react-beautiful-dnd';
import { useFormBuilderStore } from '../store/formBuilderStore';
import { FieldPalette } from '../components/form-builder/FieldPalette';
import { FormCanvas } from '../components/form-builder/FormCanvas';
import { FormFieldConfigurator } from '../components/form-builder/FormFieldConfigurator';
import { formApi } from '../lib/api';
import { FormDefinition, FieldType } from '../types/formBuilder';
import { useRouter } from 'next/router'; // For dynamic routing if editing existing form
const FormBuilderPage: React.FC = () => {
const router = useRouter();
const { formId } = router.query; // Get form ID from URL for editing
const {
currentForm,
availableFieldTypes,
addField,
reorderFields,
removeField,
setFormDefinition,
resetForm,
setTitle,
setDescription,
} = useFormBuilderStore();
const [selectedFieldId, setSelectedFieldId] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
if (formId && typeof formId === 'string') {
// Load existing form definition
formApi.getForm(formId)
.then(setFormDefinition)
.catch((err) => {
console.error("Failed to load form:", err);
setError("Failed to load form. It might not exist.");
});
} else {
resetForm(); // Start a new form if no ID
}
}, [formId, setFormDefinition, resetForm]);
const onDragEnd = (result: DropResult) => {
const { source, destination, draggableId } = result;
// Dropped outside the list
if (!destination) {
return;
}
// Dropping within the canvas to reorder
if (source.droppableId === 'form-canvas' && destination.droppableId === 'form-canvas') {
reorderFields(source.index, destination.index);
}
// Dropping from palette to canvas
else if (source.droppableId === 'field-palette' && destination.droppableId === 'form-canvas') {
addField(draggableId as FieldType); // draggableId here is the FieldType enum value
}
};
const handleSaveForm = async (publish: boolean = false) => {
setIsSaving(true);
setError(null);
setMessage(null);
try {
if (currentForm.id && router.query.formId) {
// Update existing form
await formApi.updateForm(currentForm.id, currentForm);
setMessage('Form updated successfully!');
} else {
// Create new form
const savedForm = await formApi.createForm(currentForm);
setFormDefinition(savedForm); // Update store with server-assigned ID/timestamps
setMessage('Form created successfully!');
router.replace(`/form-builder?formId=${savedForm.id}`); // Update URL
}
} catch (err: any) {
setError(err.message || 'An error occurred while saving the form.');
} finally {
setIsSaving(false);
}
};
const handleDeleteForm = async () => {
if (!currentForm.id || !window.confirm('Are you sure you want to delete this form? This cannot be undone.')) {
return;
}
setIsSaving(true); // Reusing saving state for delete
setError(null);
setMessage(null);
try {
await formApi.deleteForm(currentForm.id);
setMessage('Form deleted successfully!');
resetForm();
router.push('/form-builder'); // Redirect to new form creation
} catch (err: any) {
setError(err.message || 'An error occurred while deleting the form.');
} finally {
setIsSaving(false);
}
};
const selectedField = selectedFieldId
? currentForm.fields.find((f) => f.id === selectedFieldId)
: null;
return (
<div className="flex h-screen bg-gray-100">
{/* Field Palette */}
<div className="w-64 flex-shrink-0">
<FieldPalette availableFieldTypes={availableFieldTypes} />
</div>
<DragDropContext onDragEnd={onDragEnd}>
{/* Main Canvas */}
<div className="flex-1 p-6 flex flex-col">
<h1 className="text-3xl font-bold mb-6 text-gray-800">Form Builder</h1>
<div className="mb-6 bg-white p-4 rounded-md shadow-sm">
<input
type="text"
value={currentForm.title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Form Title"
className="text-2xl font-semibold mb-2 w-full p-2 border border-gray-300 rounded-md"
/>
<textarea
value={currentForm.description || ''}
onChange={(e) => setDescription(e.target.value)}
placeholder="Form Description (Optional)"
rows={3}
className="w-full p-2 border border-gray-300 rounded-md text-gray-600"
/>
</div>
{error && <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">{error}</div>}
{message && <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">{message}</div>}
<div className="flex-1 overflow-hidden">
<FormCanvas
fields={currentForm.fields}
onFieldSelect={setSelectedFieldId}
onRemoveField={removeField}
selectedFieldId={selectedFieldId}
/>
</div>
<div className="mt-6 flex justify-end space-x-3">
{currentForm.id && (
<button
onClick={handleDeleteForm}
className="px-6 py-3 bg-red-600 text-white rounded-md font-semibold hover:bg-red-700 disabled:opacity-50"
disabled={isSaving}
>
{isSaving ? 'Deleting...' : 'Delete Form'}
</button>
)}
<button
onClick={() => handleSaveForm()}
className="px-6 py-3 bg-blue-600 text-white rounded-md font-semibold hover:bg-blue-700 disabled:opacity-50"
disabled={isSaving}
>
{isSaving ? 'Saving...' : (currentForm.id ? 'Update Form' : 'Save Form')}
</button>
</div>
</div>
</DragDropContext>
{/* Field Configurator */}
{selectedField && (
<div className="w-80 flex-shrink-0">
<FormFieldConfigurator field={selectedField} onClose={() => setSelectedFieldId(null)} />
</div>
)}
</div>
);
};
export default FormBuilderPage;
components/DynamicFormRenderer.tsx (For Users to Fill Out Forms)
This component will take a FormDefinition and render the appropriate input fields. It will also use react-hook-form and the dynamic ZOD schema for submission and validation.
npm install react-hook-form @hookform/resolvers zod # or yarn add
// components/DynamicFormRenderer.tsx
import React from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { FormDefinition, FormField, FieldType, FormSubmissionData } from '../types/formBuilder';
import { buildZodSchema } from '../utils/zodSchemaGenerator';
import { formApi } from '../lib/api';
interface DynamicFormRendererProps {
formDefinition: FormDefinition;
onSubmitSuccess?: () => void;
}
const DynamicFormRenderer: React.FC<DynamicFormRendererProps> = ({ formDefinition, onSubmitSuccess }) => {
const dynamicSchema = buildZodSchema(formDefinition);
type FormDataSchema = z.infer<typeof dynamicSchema>;
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
reset,
} = useForm<FormDataSchema>({
resolver: zodResolver(dynamicSchema),
mode: 'onBlur', // Validate on blur
});
const onSubmit: SubmitHandler<FormDataSchema> = async (data) => {
try {
const submissionData: FormSubmissionData = {};
const formData = new FormData(); // For file uploads
for (const field of formDefinition.fields) {
const value = data[field.id];
if (field.type === FieldType.File) {
// Handle file uploads
if (value instanceof FileList && value.length > 0) {
// Append each file to FormData for backend processing
for (let i = 0; i < value.length; i++) {
formData.append(field.id, value[i]);
}
}
} else if (field.type === FieldType.Number && typeof value === 'string') {
// Convert empty string from number input back to null for ZOD
submissionData[field.id] = value === '' ? null : Number(value);
} else {
submissionData[field.id] = value;
}
}
// Append general form data as a JSON string for non-file fields
// Or, you can append each non-file field individually if your backend expects it.
// For simplicity, we'll send it as part of a single JSON string in 'data' field
// when sending with files, though it might be better to have separate endpoints
// or a more sophisticated FormData parsing on backend.
// Let's assume for simplicity we're either sending ONLY JSON or FormData WITH some JSON.
// If files are present, send FormData. Otherwise, send JSON directly.
if (formDefinition.fields.some(f => f.type === FieldType.File)) {
formData.append('data', JSON.stringify(submissionData)); // Send non-file data as string
await formApi.submitFormData(formDefinition.id, formData);
} else {
// No files, can send as JSON
await fetch(`${formApi.API_BASE_URL}/forms/${formDefinition.id}/submit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(submissionData)
}).then(res => {
if (!res.ok) throw new Error('Failed to submit form (non-file).');
return res.json();
});
}
console.log('Form submitted successfully:', data);
alert('Form submitted successfully!');
reset();
onSubmitSuccess?.();
} catch (error: any) {
console.error('Submission error:', error);
alert(`Submission failed: ${error.message}`);
}
};
return (
<div className="max-w-xl mx-auto p-6 bg-white rounded-lg shadow-md">
<h2 className="text-2xl font-bold mb-4">{formDefinition.title}</h2>
{formDefinition.description && <p className="text-gray-600 mb-6">{formDefinition.description}</p>}
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{formDefinition.fields.map((field) => (
<div key={field.id}>
<label htmlFor={field.id} className="block text-sm font-medium text-gray-700">
{field.label} {field.required && <span className="text-red-500">*</span>}
</label>
{field.description && <p className="text-xs text-gray-500 mb-1">{field.description}</p>}
{field.type === FieldType.Text && (
<input
type="text"
id={field.id}
placeholder={field.placeholder}
{...register(field.id)}
className="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
/>
)}
{field.type === FieldType.Number && (
<input
type="number"
id={field.id}
placeholder={field.placeholder}
{...register(field.id, { valueAsNumber: true })} // For number inputs
className="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
/>
)}
{field.type === FieldType.Boolean && (
<input
type="checkbox"
id={field.id}
{...register(field.id)}
className="mt-1 h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
)}
{field.type === FieldType.File && (
<input
type="file"
id={field.id}
accept={(field as FormField & { accept?: string }).accept}
multiple={(field as FormField & { multiple?: boolean }).multiple}
{...register(field.id)}
className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
/>
)}
{field.type === FieldType.Select && (
<select
id={field.id}
{...register(field.id)}
className="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
>
<option value="">Select an option</option>
{(field as FormField & { options: { label: string; value: string | number | boolean }[] }).options.map((option, idx) => (
<option key={idx} value={String(option.value)}>
{option.label}
</option>
))}
</select>
)}
{field.type === FieldType.Radio && (
<div className="mt-1 space-y-2">
{(field as FormField & { options: { label: string; value: string | number | boolean }[] }).options.map((option, idx) => (
<label key={idx} className="inline-flex items-center">
<input
type="radio"
id={`${field.id}-${idx}`}
value={String(option.value)}
{...register(field.id)}
className="form-radio h-4 w-4 text-blue-600 transition duration-150 ease-in-out"
/>
<span className="ml-2 text-gray-700">{option.label}</span>
</label>
))}
</div>
)}
{field.type === FieldType.CheckboxGroup && (
<div className="mt-1 space-y-2">
{(field as FormField & { options: { label: string; value: string | number | boolean }[] }).options.map((option, idx) => (
<label key={idx} className="inline-flex items-center">
<input
type="checkbox"
id={`${field.id}-${idx}`}
value={String(option.value)}
{...register(field.id)}
className="form-checkbox h-4 w-4 text-blue-600 transition duration-150 ease-in-out"
/>
<span className="ml-2 text-gray-700">{option.label}</span>
</label>
))}
</div>
)}
{errors[field.id] && (
<p className="mt-1 text-sm text-red-600">{errors[field.id]?.message?.toString()}</p>
)}
</div>
))}
<button
type="submit"
disabled={isSubmitting}
className="mt-6 w-full py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
>
{isSubmitting ? 'Submitting...' : 'Submit Form'}
</button>
</form>
</div>
);
};
export default DynamicFormRenderer;
2. Backend Module (FastAPI, Pydantic, SQLAlchemy, PostgreSQL)
A. Pydantic Models
These mirror your frontend TypeScript interfaces for data validation.
# app/schemas.py
from pydantic import BaseModel, Field, HttpUrl, validator
from typing import List, Literal, Optional, Union, Dict, Any
from datetime import datetime
class FormOptionBase(BaseModel):
label: str
value: Union[str, int, bool]
class FormFieldBase(BaseModel):
id: str = Field(..., description="Unique ID for the field within the form")
label: str
required: bool = False
placeholder: Optional[str] = None
description: Optional[str] = None
default_value: Optional[Union[str, int, bool, List[Union[str, int, bool]]]] = None # For CheckboxGroup, this might be a list
class TextField(FormFieldBase):
type: Literal["text"] = "text"
min_length: Optional[int] = None
max_length: Optional[int] = None
class NumberField(FormFieldBase):
type: Literal["number"] = "number"
min: Optional[float] = None
max: Optional[float] = None
class BooleanField(FormFieldBase):
type: Literal["boolean"] = "boolean"
class FileField(FormFieldBase):
type: Literal["file"] = "file"
accept: Optional[str] = None # e.g., "image/*, .pdf"
multiple: bool = False
class SelectField(FormFieldBase):
type: Literal["select"] = "select"
options: List[FormOptionBase]
class RadioField(FormFieldBase):
type: Literal["radio"] = "radio"
options: List[FormOptionBase]
class CheckboxGroupField(FormFieldBase):
type: Literal["checkboxGroup"] = "checkboxGroup"
options: List[FormOptionBase]
# Union type for all possible field types
FormField = Union[TextField, NumberField, BooleanField, FileField, SelectField, RadioField, CheckboxGroupField]
class FormDefinitionBase(BaseModel):
title: str
description: Optional[str] = None
fields: List[FormField]
class FormDefinitionCreate(FormDefinitionBase):
id: Optional[str] = None # Allow client to provide, or backend generates
class FormDefinitionUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
fields: Optional[List[FormField]] = None
class FormDefinitionOut(FormDefinitionBase):
id: str
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class FormSubmissionCreate(BaseModel):
# This model will be used when the frontend sends JSON data
# For file uploads, you'd typically use a separate Form data parsing
# FastAPI can handle mixed data (JSON + Files) with `Request` object and `form.read()`,
# or using `UploadFile` for specific fields.
# For simplicity, if files are involved, `data` might come as a JSON string within FormData.
data: Dict[str, Any]
class FormSubmissionOut(BaseModel):
id: str
form_id: str
submitted_at: datetime
data: Dict[str, Any] # This will store the actual submitted field values
class Config:
from_attributes = True
B. SQLAlchemy Models and Database Setup
# app/database.py
from sqlalchemy import create_engine, Column, String, DateTime, ForeignKey, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
import os
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://user:password@localhost/mydb")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class FormDefinition(Base):
__tablename__ = "form_definitions"
id = Column(String, primary_key=True, index=True) # UUID string
title = Column(String, index=True)
description = Column(Text, nullable=True)
definition = Column(JSONB, nullable=False) # Stores the Pydantic model as JSONB
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, onupdate=func.now(), server_default=func.now())
class FormSubmission(Base):
__tablename__ = "form_submissions"
id = Column(String, primary_key=True, index=True) # UUID string
form_id = Column(String, ForeignKey("form_definitions.id"), nullable=False)
submitted_at = Column(DateTime, server_default=func.now())
data = Column(JSONB, nullable=False) # Stores the submitted form data
# Call this once to create tables
def create_db_and_tables():
Base.metadata.create_all(engine)
C. CRUD Operations
# app/crud.py
from sqlalchemy.orm import Session
from . import models, schemas
from uuid import uuid4
import json
import os
# Directory for file uploads
UPLOAD_DIR = "uploads"
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
def get_form_definition(db: Session, form_id: str):
return db.query(models.FormDefinition).filter(models.FormDefinition.id == form_id).first()
def get_form_definitions(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.FormDefinition).offset(skip).limit(limit).all()
def create_form_definition(db: Session, form: schemas.FormDefinitionCreate):
form_id = form.id if form.id else str(uuid4())
db_form = models.FormDefinition(
id=form_id,
title=form.title,
description=form.description,
definition=form.model_dump_json(by_alias=True) # Convert Pydantic model to JSON string
)
db.add(db_form)
db.commit()
db.refresh(db_form)
# Ensure 'definition' is loaded as a dict for schemas.FormDefinitionOut
db_form.definition = json.loads(db_form.definition)
return db_form
def update_form_definition(db: Session, form_id: str, form_update: schemas.FormDefinitionUpdate):
db_form = db.query(models.FormDefinition).filter(models.FormDefinition.id == form_id).first()
if db_form:
current_definition = schemas.FormDefinitionCreate.model_validate(db_form.definition)
update_data = form_update.model_dump(exclude_unset=True)
# Apply updates to the current definition
updated_fields = update_data.get('fields', current_definition.fields)
if 'fields' in update_data: # If fields explicitly sent, replace
current_definition.fields = updated_fields
if 'title' in update_data:
current_definition.title = update_data['title']
if 'description' in update_data:
current_definition.description = update_data['description']
db_form.title = current_definition.title
db_form.description = current_definition.description
db_form.definition = current_definition.model_dump_json(by_alias=True)
db.add(db_form)
db.commit()
db.refresh(db_form)
db_form.definition = json.loads(db_form.definition) # Ensure dict for output
return db_form
def delete_form_definition(db: Session, form_id: str):
db_form = db.query(models.FormDefinition).filter(models.FormDefinition.id == form_id).first()
if db_form:
db.delete(db_form)
db.commit()
return db_form
# --- Form Submission CRUD ---
def create_form_submission(db: Session, form_id: str, submission_data: Dict[str, Any]):
db_submission = models.FormSubmission(
id=str(uuid4()),
form_id=form_id,
data=submission_data
)
db.add(db_submission)
db.commit()
db.refresh(db_submission)
return db_submission
def get_form_submissions_by_form_id(db: Session, form_id: str, skip: int = 0, limit: int = 100):
return db.query(models.FormSubmission).filter(models.FormSubmission.form_id == form_id).offset(skip).limit(limit).all()
# File handling utility (simplified, needs robust error handling and security)
async def save_upload_file(field_id: str, file_upload: UploadFile) -> str:
# Generate a unique filename to prevent clashes
file_extension = os.path.splitext(file_upload.filename)[1]
unique_filename = f"{uuid4()}{file_extension}"
file_path = os.path.join(UPLOAD_DIR, unique_filename)
async with aiofiles.open(file_path, 'wb') as out_file:
while content := await file_upload.read(1024 * 1024): # Read in 1MB chunks
await out_file.write(content)
return file_path # Return path or URL for storage
D. FastAPI Endpoints
# app/main.py
from fastapi import FastAPI, Depends, HTTPException, status, UploadFile, File, Form, Request
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from typing import List, Dict, Any
from . import crud, models, schemas
from .database import SessionLocal, engine, create_db_and_tables
import json
import os
import aiofiles # For async file writing
# Create DB tables on startup
create_db_and_tables()
app = FastAPI(
title="Form Builder API",
description="API for creating dynamic forms and capturing submissions.",
version="0.1.0",
)
# CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust this to your frontend URL in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# --- Form Definition Endpoints ---
@app.post("/forms", response_model=schemas.FormDefinitionOut, status_code=status.HTTP_201_CREATED)
def create_form(form: schemas.FormDefinitionCreate, db: Session = Depends(get_db)):
db_form = crud.create_form_definition(db, form)
return db_form
@app.get("/forms", response_model=List[schemas.FormDefinitionOut])
def read_forms(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
forms = crud.get_form_definitions(db, skip=skip, limit=limit)
# Convert JSONB strings back to dicts for Pydantic serialization
for form in forms:
form.definition = json.loads(form.definition)
return forms
@app.get("/forms/{form_id}", response_model=schemas.FormDefinitionOut)
def read_form(form_id: str, db: Session = Depends(get_db)):
db_form = crud.get_form_definition(db, form_id)
if db_form is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Form not found")
# Convert JSONB string back to dict
db_form.definition = json.loads(db_form.definition)
return db_form
@app.put("/forms/{form_id}", response_model=schemas.FormDefinitionOut)
def update_form(form_id: str, form: schemas.FormDefinitionUpdate, db: Session = Depends(get_db)):
db_form = crud.update_form_definition(db, form_id, form)
if db_form is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Form not found")
return db_form
@app.delete("/forms/{form_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_form(form_id: str, db: Session = Depends(get_db)):
db_form = crud.delete_form_definition(db, form_id)
if db_form is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Form not found")
return
# --- Form Submission Endpoints ---
@app.post("/forms/{form_id}/submit", response_model=schemas.FormSubmissionOut, status_code=status.HTTP_201_CREATED)
async def submit_form_data(
form_id: str,
request: Request,
db: Session = Depends(get_db)
):
# Retrieve form definition to validate submitted data against it
form_def_record = crud.get_form_definition(db, form_id)
if not form_def_record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Form not found")
form_definition = schemas.FormDefinitionOut.model_validate(json.loads(form_def_record.definition))
submitted_data = {}
file_fields = [f for f in form_definition.fields if f.type == schemas.FieldType.File]
# Check content type to distinguish between JSON and FormData
content_type = request.headers.get('content-type', '')
if 'application/json' in content_type:
try:
raw_data = await request.json()
submitted_data = schemas.FormSubmissionCreate(data=raw_data).data
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid JSON body: {e}")
elif 'multipart/form-data' in content_type:
try:
form_data = await request.form()
# If `data` is a JSON string within FormData
if 'data' in form_data and isinstance(form_data['data'], str):
submitted_data = json.loads(form_data['data'])
else: # Fallback for non-jsonified form data
for key, value in form_data.items():
if isinstance(value, str):
submitted_data[key] = value
elif isinstance(value, UploadFile):
pass # Files handled separately
# Process files
for field in file_fields:
file_uploads = form_data.getlist(field.id) # Get all files for this field
if file_uploads:
file_paths = []
for file_upload in file_uploads:
if isinstance(file_upload, UploadFile):
# Save file to disk/S3 and get its path/URL
saved_path = await crud.save_upload_file(field.id, file_upload)
file_paths.append(saved_path)
submitted_data[field.id] = file_paths # Store list of paths
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid form data: {e}")
else:
raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="Content-Type must be application/json or multipart/form-data")
# Perform server-side validation against the Pydantic model for the form structure
# This ensures that even if frontend validation is bypassed, backend catches it.
try:
# Dynamically build a Pydantic model for submission validation
submission_model_fields = {}
for field_def in form_definition.fields:
# Map field types to Pydantic types
pydantic_type = Any # Default
if field_def.type == schemas.FieldType.Text:
pydantic_type = str
elif field_def.type == schemas.FieldType.Number:
pydantic_type = Union[int, float]
elif field_def.type == schemas.FieldType.Boolean:
pydantic_type = bool
elif field_def.type == schemas.FieldType.File:
# Store paths to files as list of strings
pydantic_type = List[str] if field_def.multiple else str
elif field_def.type in [schemas.FieldType.Select, schemas.FieldType.Radio]:
pydantic_type = Union[str, int, bool] # Based on form options' value type
elif field_def.type == schemas.FieldType.CheckboxGroup:
pydantic_type = List[Union[str, int, bool]]
if not field_def.required:
pydantic_type = Optional[pydantic_type]
# Add more specific validation from form_definition here (min_length, max, options etc.)
# This would require dynamically creating validators or subclasses for each field type.
# For brevity, we'll rely on the frontend ZOD schema for more granular value validation,
# and Pydantic here for structural and type validation.
submission_model_fields[field_def.id] = (pydantic_type, Field(... if field_def.required else None)) # Use Pydantic Field for required/optional
# Create a dynamic Pydantic model at runtime
DynamicSubmissionModel = type(
'DynamicSubmissionModel',
(BaseModel,),
{'__annotations__': {k: v[0] for k, v in submission_model_fields.items()},
**{k: v[1] for k, v in submission_model_fields.items()}}
)
# Validate submitted data using the dynamically created model
validated_data = DynamicSubmissionModel(**submitted_data).model_dump()
except Exception as e:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Validation error: {e.errors() if hasattr(e, 'errors') else e}")
db_submission = crud.create_form_submission(db, form_id, validated_data)
return db_submission
@app.get("/forms/{form_id}/submissions", response_model=List[schemas.FormSubmissionOut])
def read_form_submissions(form_id: str, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
submissions = crud.get_form_submissions_by_form_id(db, form_id, skip=skip, limit=limit)
return submissions
# To run the backend:
# 1. Make sure you have PostgreSQL running and a database created.
# 2. Set the DATABASE_URL environment variable:
# export DATABASE_URL="postgresql://user:password@localhost/yourdb"
# 3. Install dependencies:
# pip install fastapi "uvicorn[standard]" psycopg2-binary sqlalchemy pydantic aiofiles
# 4. Run:
# uvicorn app.main:app --reload
Improvements & Weaknesses
Strengths of Your Chosen Architecture:
- Type Safety (End-to-End): TypeScript on frontend, Pydantic on backend, and consistent data modeling significantly reduce runtime errors and improve developer experience.
- Robust Validation: ZOD (frontend) and Pydantic (backend) provide excellent declarative validation. Dynamically generating schemas is a powerful pattern.
- Modern State Management: Zustand is lightweight, performant, and scales well for complex global state needs.
- Asynchronous Backend: FastAPI is incredibly fast and efficient, perfect for I/O-bound tasks like database interactions and file uploads.
- Flexible Data Storage: Storing form definitions as
JSONB in PostgreSQL is ideal. It allows for schemaless flexibility while still leveraging PostgreSQL's powerful JSON querying capabilities if needed.
- ORM Benefits: SQLAlchemy provides an object-oriented way to interact with your database, reducing raw SQL and improving maintainability.
Weaknesses & Potential Improvements:
-
Authentication and Authorization (Major Weakness):
- Weakness: Currently, anyone can create, update, delete forms, or view/submit data. This is a critical security flaw for a real-world application.
- Improvement: Implement robust authentication (e.g., JWT, OAuth2) for users building forms and possibly for users submitting data (e.g., if forms are private). Implement authorization checks to ensure users only access/modify forms they are permitted to. FastAPI has excellent support for security features.
-
File Uploads Storage & Serving:
- Weakness: The current backend logic saves files locally. This is generally not scalable or robust for production (e.g., crashes, multi-instance deployments).
- Improvement: Store files in a dedicated object storage service like AWS S3, Google Cloud Storage, or Azure Blob Storage. The backend should return URLs to these files, not local paths. This also implies managing file URLs in your
FormSubmission data JSONB.
-
Advanced Form Features:
- Weakness: Your current field types are foundational.
- Improvement:
- Conditional Logic: "If field A is X, then show field B." This is a complex but often requested feature for form builders.
- Calculated Fields: Fields whose value depends on other fields (e.g.,
total = price * quantity).
- Repeating Sections/Arrays: Allowing users to add multiple instances of a group of fields (e.g., "Add another family member").
- Date/Time Pickers: Dedicated components for date and time input.
- Rich Text Editor: For longer text inputs.
- Layout/Sections: Grouping fields into sections or columns for better visual organization.
-
Frontend UX/UI:
- Weakness: The current UI implementation is functional but basic.
- Improvement:
- Component Library: Integrate a UI library like Tailwind CSS (which you seem to be using with the utility classes), Chakra UI, Material UI, or Ant Design for a more polished look and consistent components.
- Undo/Redo: Essential for a builder interface.
- A dedicated live preview mode that renders the form as a user would see it.
This setup provides a solid foundation. Addressing the weaknesses, especially security and file storage, would be the next critical steps for a production-ready application. Good luck!