Created
September 22, 2020 16:26
-
-
Save schicks/74c1b8c1474a13fdd4ba7fd2bdcf56ee to your computer and use it in GitHub Desktop.
FastAPI static types
This file contains 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 .schemas import HealthCheckModel, HealthCheckDict | |
@app.get("/health-check", response_model=HealthCheckModel) # FastAPI uses pydantic version | |
async def healthcheck() -> HealthCheckDict: # route annotated with TypedDict version for static validation | |
return {'status': 'ok'} |
This file contains 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 typing import TypedDict, Type | |
from pydantic import BaseModel, create_model | |
def model_from_td(name: str, td: Type) -> Type[BaseModel]: | |
return create_model( | |
name, | |
**{ | |
key: (value, ...) | |
for key, value in td.__annotations__.items() | |
} | |
) | |
class HealthCheckDict(TypedDict): # create model as TypedDict | |
status: str | |
HealthCheckModel = model_from_td('HealthCheckModel', HealthCheckDict) # generate pydantic model from TypedDict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment