Created
July 15, 2021 13:27
-
-
Save Hultner/228293e9316a9b72ef6f01766be3232a to your computer and use it in GitHub Desktop.
Example of patching schema for float Enum query parameters in FastAPI.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum | |
from fastapi import FastAPI, Depends, HTTPException, Query | |
from pydantic import BaseModel, ValidationError | |
app = FastAPI() | |
class Number(float, Enum): | |
ten = 10.0 | |
twelve = 12.0 | |
class MyModel(BaseModel): | |
num: Number | |
async def number_parameter( | |
num: float = Query(..., **MyModel.schema()["definitions"]["Number"]) | |
) -> Number: | |
try: | |
tmp_num = MyModel(num=num) | |
return tmp_num.num | |
except ValidationError as err: | |
# breakpoint() | |
raise HTTPException(detail=err.errors(), status_code=400) | |
# MyModel(num=10.0) # <- This works! | |
@app.get("/") | |
async def root(num: Number = Depends(number_parameter)): | |
return {"message": f"Hello {num}"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment