green snake
Photo by Pixabay on Pexels.com

Type Annotations in FastAPI (Beginner-Friendly Complete Guide)

✅ Introduction: Why Type Annotations Matter

FastAPI leverages Python’s type hints to enable automatic validation and API documentation generation. By explicitly defining types for variables, you enhance IDE auto-completion, reduce bugs, and improve code readability and maintainability.


1. What Are Type Hints in Python?

Although Python is dynamically typed, adding type hints like str or int to variables and functions allows static analysis tools (like MyPy or Pyright) to detect bugs early and enhances code completion in IDEs.

def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."

2. Using Types in FastAPI (Part 1): Path and Query Parameters

In FastAPI endpoints, specifying parameter types enables automatic type casting and validation.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}
  • item_id must be an integer. Invalid input returns a 400 error.
  • q: str | None = None defines an optional query string.

3. Using Types in FastAPI (Part 2): Validating Request Body with Pydantic

When receiving a request body, use a Pydantic BaseModel to define the expected structure and types.

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    price: float
    is_offer: Optional[bool] = None

app = FastAPI()

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}
  • Invalid data automatically triggers a 400 response.
  • Optional fields can be omitted in the request body.

4. Benefits of Type Hints ✨

Benefit Description
IDE Support & Static Analysis Better auto-completion and static checking with MyPy or Pyright.
Automatic Validation FastAPI and Pydantic validate input based on types.
Auto-Generated Docs Swagger UI is generated from type annotations and schemas.

5. Advanced Typing: Lists, Dicts, Optional, Union

You can type complex structures and optional/union values too.

from typing import List, Dict, Optional, Union

def complex_example(ids: List[int], options: Dict[str, float]):
    pass

value: Union[int, str] = 42
name: Optional[str] = None  # Accepts str or None

6. Strict Typing and Custom Validation with Pydantic

Pydantic supports strict types such as StrictStr and custom validators with @validator.

from pydantic import BaseModel, StrictStr, validator

class Product(BaseModel):
    title: StrictStr
    price: float

    @validator('price')
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Price must be a positive number')
        return v

7. Workflow for Effective Type Usage

  1. Add type hints to function arguments and return values.
  2. Use Pydantic models for structured data validation.
  3. Test your endpoints using Swagger UI or unit tests.
  4. Integrate with tools like MyPy or Pyright for static checks.

✅ Summary

In FastAPI, type annotations are vital for building robust APIs. They enhance safety, readability, and allow automatic user input validation. Start with simple hints, then explore more advanced types like Optional, Union, and Pydantic models to build modern and resilient web applications.

Harness the power of typing to unlock the full potential of Python and FastAPI!

By greeden

Leave a Reply

Your email address will not be published. Required fields are marked *

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)