Skip to content

Instantly share code, notes, and snippets.

@duonghuuphuc
Created March 27, 2025 07:37
Show Gist options
  • Save duonghuuphuc/fae77dda5ca9dbcd1d624a4e655a0e18 to your computer and use it in GitHub Desktop.
Save duonghuuphuc/fae77dda5ca9dbcd1d624a4e655a0e18 to your computer and use it in GitHub Desktop.
CS504070 - Homework 9: Advanced Models

CS504070 - Homework 9


Exercise 1: UUID and Datetime Fields

Create a FastAPI endpoint that receives and returns data containing both UUID and datetime fields.

Requirements:

  • Create a Pydantic model Event containing the following fields:
    • id: UUID (auto-generated if not provided).
    • name: String.
    • timestamp: Datetime (auto-generated as current UTC time if not provided).
  • The endpoint should receive an Event model and return the created event with assigned values.

Exercise 2: Nested Models

Create a FastAPI endpoint to handle a complex nested request body.

Requirements:

  • Define a nested Pydantic model structure as follows:
class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    user_id: UUID
    username: str
    email: str
    address: Address
  • The endpoint should accept a User model and return it.

Exercise 3: List Fields

Design a FastAPI endpoint to handle list fields within the request body.

Requirements:

  • Create the following models:
class Product(BaseModel):
    product_id: UUID
    name: str
    price: float

class Order(BaseModel):
    order_id: UUID
    products: List[Product]
    order_date: datetime
  • Implement a POST endpoint that receives an Order and returns the order details.

Exercise 4: Advanced Nested Structures and Lists

Build a FastAPI endpoint with a deeply nested structure containing lists and datetime fields.

Requirements:

  • Define models as follows:
class Author(BaseModel):
    author_id: UUID
    name: str
    email: Optional[str]

class Comment(BaseModel):
    comment_id: UUID
    content: str
    created_at: datetime
    author: Author

class BlogPost(BaseModel):
    post_id: UUID
    title: str
    content: str
    published_at: datetime
    tags: List[str]
    comments: List[Comment]
  • The endpoint should accept a BlogPost object and return the received post data.

Exercise 5: Validation and Nested UUID/Datetime

Enhance validation on UUID and datetime fields within nested structures.

Requirements:

  • Implement a model:
class TaskDetail(BaseModel):
    detail_id: UUID
    description: str
    deadline: datetime

class Task(BaseModel):
    task_id: UUID
    title: str
    created_at: datetime
    details: List[TaskDetail]
  • Validate that deadline in each TaskDetail must be greater than the current datetime.
  • Write a POST endpoint that validates this model and returns the task if validation passes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment