Code Examples

Learn Tyck through practical examples. Copy, paste, and customize for your projects.

Basic Interface

Basics

Create a simple user model with validation constraints

REST API Schemas

API Design

Define request and response schemas for a REST API

Nested Models

Advanced

Work with complex nested data structures

Application Configuration

Configuration

Type-safe application configuration with validation

Class-Based Models

Basics

Use @model decorator for schemas with custom methods

Handling Validation Errors

Validation

Catch and process validation errors with detailed messages

Hybrid: Tyck + Pydantic

Hybrid (Tyck + Pydantic)

Use Tyck and Pydantic together in the same project

Schema Transformations

Utilities

Use pick, omit, partial, extend, and merge utilities

Basics

Basic Interface

Create a simple user model with validation constraints

basic_interface.py
from tyck import interface, string, integer, optional, number, array
  
  # Define a User schema with validation
  User = interface({
      'id': integer.positive(),
      'username': string.min(3).max(30),
      'email': string.email(),
      'age': optional(integer.range(13, 120)),
      'roles': array(string).default(['user']),
  })
  
  # Create and validate a user
  user = User(
      id=1,
      username="john_doe",
      email="john@example.com",
      age=28,
  )
  
  # Serialize to dictionary
  print(user.model_dump())

Output

{
    'id': 1,
    'username': 'john_doe',
    'email': 'john@example.com',
    'age': 28,
    'roles': ['user']
  }