Search code examples
pythonfastapipydantic

How to Replace Pydantic's constr for use outside of BaseModel in FastAPI?


I'm working with FastAPI and Pydantic for a project where I've used constr for string validation. This has been particularly useful for ensuring that string inputs adhere to specific constraints, like length and format, directly in the route function signatures.

enter image description here

Here's an example of how I've been using it:

from pydantic import constr
from fastapi import FastAPI, HTTPException

SiteCode = constr(strict=True, to_upper=True, max_length=4)

app = FastAPI()

@app.get("/{site_code}", summary="Read a site")
async def get_site(site_code: SiteCode) -> str:
    return "..."

However, I've learned that constr is deprecated, and I'm looking for a modern replacement that aligns with current best practices in Pydantic and FastAPI. My goal is to maintain the same level of validation (e.g., strict, to_upper, max_length) for parameters passed directly to route functions, not just within Pydantic models.


Solution

  • It's said in the documentation that you should use Annotated with StringConstraints instead of constr:

    SiteCode = Annotated[str, StringConstraints(strict=True, to_upper=True, max_length=4)]
    
    @app.get("/{site_code}", summary="Read a site")
    async def get_site(site_code: SiteCode) -> str:
        return site_code
    
    

    https://docs.pydantic.dev/2.6/api/types/#pydantic.types.constr