Skip to content

FastAPI Todo API with advanced Pydantic validation: field validators, model validators, and cross-field validation rules. Comprehensive testing with pytest.

Notifications You must be signed in to change notification settings

jandaghi14/fastapi-custom-validators

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI Custom Validators

A FastAPI project demonstrating advanced Pydantic validation techniques including field validators, model validators, and cross-field validation rules.

🎯 Project Overview

This project showcases professional validation patterns in FastAPI using Pydantic's validation features. Built as part of my journey to becoming a Python developer, this API implements comprehensive validation for a Todo management system.

✨ Features

  • Field Validation: String length constraints, numeric ranges
  • Custom Validators: Whitespace trimming, empty string handling
  • Cross-Field Validation: Business rules across multiple fields
  • Proper HTTP Status Codes: 201, 404, 422 responses
  • Comprehensive Testing: 100% test coverage with pytest
  • Automatic API Documentation: Interactive docs at /docs

πŸ› οΈ Technologies Used

  • FastAPI: Modern Python web framework
  • Pydantic: Data validation using Python type hints
  • Uvicorn: ASGI server
  • pytest: Testing framework
  • Python 3.10+

πŸ“‹ Validation Rules Implemented

Field-Level Validation

  • Title:
    • Required field
    • 1-100 characters
    • Cannot be only whitespace
    • Automatically trimmed
  • Description:
    • Optional field
    • Max 500 characters
    • Empty strings converted to None
    • Automatically trimmed
  • Priority:
    • Required integer
    • Must be between 1-5

Model-Level Validation

  • Urgent Todos: Priority 5 (urgent) todos must have a description

πŸš€ Installation & Setup

Prerequisites

  • Python 3.10 or higher
  • pip

Install Dependencies

# Clone the repository
git clone https://github.com/YOUR_USERNAME/fastapi-custom-validators.git
cd fastapi-custom-validators

# Install required packages
pip install fastapi uvicorn pytest

πŸ’» Running the Application

# Start the server
uvicorn fastapi_custom_validators:app --reload

The API will be available at:

πŸ§ͺ Running Tests

# Run all tests
pytest test_fastapi_custom_validators.py -v

# Run with coverage
pytest test_fastapi_custom_validators.py -v --cov

πŸ“‘ API Endpoints

Create Todo

POST /todos
Content-Type: application/json

{
  "title": "Buy groceries",
  "description": "Milk, eggs, bread",
  "priority": 3
}

Response (201 Created):

{
  "id": 1,
  "title": "Buy groceries",
  "description": "Milk, eggs, bread",
  "priority": 3,
  "completed": false
}

Get All Todos

GET /todos

Response (200 OK):

[
  {
    "id": 1,
    "title": "Buy groceries",
    "description": "Milk, eggs, bread",
    "priority": 3,
    "completed": false
  }
]

Get Single Todo

GET /todos/{todo_id}

Response (200 OK):

{
  "id": 1,
  "title": "Buy groceries",
  "description": "Milk, eggs, bread",
  "priority": 3,
  "completed": false
}

Response (404 Not Found):

{
  "detail": "Todo not found"
}

⚠️ Validation Examples

Valid Requests βœ…

// Minimal valid todo
{"title": "Buy milk", "priority": 3}

// With description
{"title": "Fix bug", "description": "Critical production issue", "priority": 5}

// Whitespace is trimmed
{"title": "  Task  ", "priority": 2}
// Saved as: "Task"

Invalid Requests ❌

// Empty title (422 Error)
{"title": "", "priority": 3}

// Whitespace-only title (422 Error)
{"title": "   ", "priority": 3}

// Title too long (422 Error)
{"title": "x".repeat(101), "priority": 3}

// Priority out of range (422 Error)
{"title": "Task", "priority": 6}

// Urgent todo without description (422 Error)
{"title": "Critical task", "priority": 5}
// Error: "Urgent todos must have a description"

πŸ“š What I Learned

  • Pydantic Field Constraints: Using Field() for min/max length, numeric ranges
  • Custom Field Validators: @field_validator for custom validation logic
  • Model Validators: @model_validator for cross-field business rules
  • Proper Error Handling: HTTPException with appropriate status codes
  • Professional Testing: Comprehensive test coverage including edge cases
  • API Documentation: Automatic OpenAPI/Swagger documentation

πŸ”„ Project Evolution

This project is part of my Python learning roadmap:

  • Day 91: Basic FastAPI application (fastapi-hello-api)
  • Day 92: CRUD operations (fastapi-todo-crud)
  • Day 93: Advanced validation (this project) ⭐

πŸ“ Future Enhancements

  • Database integration (SQLite/PostgreSQL)
  • User authentication with JWT
  • Update and Delete endpoints
  • Pagination for GET /todos
  • Filtering and sorting
  • Deployment to production

🀝 Contributing

This is a learning project, but feedback and suggestions are welcome! Feel free to open an issue or submit a pull request.

πŸ“„ License

This project is open source and available under the MIT License.

πŸ‘¨β€πŸ’» Author

Your Name

  • GitHub: @jandaghi14
  • LinkedIn: [ali-jandaghi-9a3188b1]
  • Learning Journey: Python Developer Roadmap (Days 1-180)

πŸ™ Acknowledgments

Built as part of my self-taught Python developer journey. Special focus on professional coding practices, testing, and API design patterns.


Day 93 of 180 - Advanced Pydantic Validation βœ…

About

FastAPI Todo API with advanced Pydantic validation: field validators, model validators, and cross-field validation rules. Comprehensive testing with pytest.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages