3

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}

2
  • I think you could write pydantic model with a validator Commented Jul 8, 2021 at 13:00
  • 1
    from typing import Union, Literal, version: Union[Literal['active'], int] could work? Commented Jul 8, 2021 at 13:27

1 Answer 1

4

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]

Sign up to request clarification or add additional context in comments.

3 Comments

It is not clear how to use that to solve the problem in the original post. What do you put in the app.get decorator and in the function signature? def endpoint(version:Version)? def endpoint(version:Version.version) ? Something else?
It is enough that the def becomes def endpoint(version: Version):
Thank you. So this is my understanding of how it works (I haven't seen this documented anywhere): FASTApi looks into the fields of the model (here Version) and if it finds a field name that matches the argument name of the decorated function, it uses the type of that field to validate the url parameter. Am I correct? Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.