Skip to content

Instantly share code, notes, and snippets.

@schicks
Created September 22, 2020 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schicks/74c1b8c1474a13fdd4ba7fd2bdcf56ee to your computer and use it in GitHub Desktop.
Save schicks/74c1b8c1474a13fdd4ba7fd2bdcf56ee to your computer and use it in GitHub Desktop.
FastAPI static types
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'}
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