Skip to content

Instantly share code, notes, and snippets.

@mfurquimdev
Created February 14, 2024 20:49
Show Gist options
  • Save mfurquimdev/38e0fff75e3f6d5ead3de3e7bc8caee9 to your computer and use it in GitHub Desktop.
Save mfurquimdev/38e0fff75e3f6d5ead3de3e7bc8caee9 to your computer and use it in GitHub Desktop.
import uvicorn
from fastapi import FastAPI
from view import router as sample_router
app = FastAPI()
app.include_router(sample_router)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8181)
"""Define sample models."""
from typing import Annotated
from fastapi import Body
from fastapi import Query
from pydantic import BaseModel
class SampleResponse(BaseModel):
query_name: str
query_age: int
body_name: str
body_age: int
sample_path_params: str
class SampleQueryParams(BaseModel):
query_name: Annotated[
str,
Query(
...,
title="Query Name",
description="Query Name of the sample",
),
]
query_age: Annotated[
int,
Query(
default=21,
title="Query Age",
description="Query Age of the sample",
gt=18,
),
]
class SampleBodyParams(BaseModel):
body_name: Annotated[
str,
Body(
...,
title="Body Name",
description="Body Name of the sample",
),
]
body_age: Annotated[
int,
Body(
default=21,
title="Body Age",
description="Body Age of the sample",
gt=18,
),
]
__all__ = [SampleQueryParams, SampleBodyParams]
from typing import Annotated
from fastapi import APIRouter
from fastapi import Depends
from fastapi import Path
from .model import SampleBodyParams
from .model import SampleQueryParams
from .model import SampleResponse
router = APIRouter(
prefix="/sample",
tags=["sample"],
)
@router.post(
"/{sample_path_params}",
summary="Sample endpoint",
response_description="Sample response",
response_model=SampleResponse,
)
def trigger_simulation(
sample_query_params: Annotated[SampleQueryParams, Depends()],
sample_body_params: SampleBodyParams,
sample_path_params: Annotated[str, Path(title="Sample Path Params")],
):
print(
f"POST /sample start with query {sample_query_params}, body {sample_body_params} and path "
f"{sample_path_params}"
)
response_dict = {
**sample_query_params.dict(),
**sample_body_params.dict(),
**{"sample_path_params": sample_path_params},
}
print(response_dict)
response: SampleResponse = SampleResponse(**response_dict)
print(
f"POST /sample finished with data {sample_query_params}, body {sample_body_params} and "
f"path {sample_path_params} and response {response}"
)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment