Search code examples
pythonfastapipython-typingpydantic

FastAPI path parameter validation for a fixed string or any valid integer


I need to parse version parameter from URL path in FastAPI endpoint. The valid value for version parameter is either a fixed string e.g. active or any integer e.g. 1.

Is there an elegant way to make FastAPI or pydantic validate this path parameter with such rules so that I don't have to perform validation manually?

@app.get("/{version}")
def endpoint(version):
    # version could be either 'active' or valid integer e.g. 1
    return {"version": version}


Solution

  • What you are looking to do (have the choice between two types) is Union.

    Example:

    from typing import Union
    from pydantic import BaseModel
    
    class Version(BaseModel):
        version: Union[int, str]
    
    

    Warning ! Union tries to match the type of parameter to the given order of Union and stops at the first match, i.e. it will try in the example below, to find an INT first , then second, an STR. In some cases, this is of great importance.

    Then comes the fact of wanting to have a fixed value. This is a Literal.

    The Union and the Literal together would therefore give this:

    from typing import Union, Literal
    from pydantic import BaseModel
    
    class Version(BaseModel):
        version: Union[Literal['active'], int]