From fba951459fa0c62d55c0048a453f6af95edc7542 Mon Sep 17 00:00:00 2001 From: zhavir Date: Fri, 26 Aug 2022 19:13:24 +0200 Subject: [PATCH] feat(main): setup fastapi app with openapi spec (#4) --- docker-compose.yaml | 2 +- requirements.txt | 2 ++ src/app/main.py | 54 +++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 9c2035c..56ccaeb 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -8,7 +8,7 @@ services: ports: - 9001:9001 volumes: - - ./app:/app + - ./src/app:/src/app networks: - test diff --git a/requirements.txt b/requirements.txt index e69de29..3941912 100644 --- a/requirements.txt +++ b/requirements.txt @@ -0,0 +1,2 @@ +fastapi==0.80.0 +uvicorn[standard]==0.18.3 diff --git a/src/app/main.py b/src/app/main.py index 4f94abe..3fdf7a0 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -1,2 +1,52 @@ -if __name__ == '__main__': - print("hello world") +import argparse + +import uvicorn +from fastapi import FastAPI, APIRouter +from fastapi.openapi.utils import get_openapi + + +APP_VERSION = 1.0 +SERVICE_NAME = 'Password Generator' +SERVICE_DESCRIPTION = 'The password generator service' + +app = FastAPI(title=SERVICE_NAME, description=SERVICE_DESCRIPTION) + +# Main routers for API versioning +router_api = APIRouter() +router_api_v1 = APIRouter() +# Registration of routes + + +# Finalizing setup of router with FastAPI app +router_api.include_router(router_api_v1, prefix="/v1") +app.include_router(router_api, prefix="/api") + + +# OpenAPI +def custom_openapi(): + if app.openapi_schema: + return app.openapi_schema + openapi_schema = get_openapi( + title=SERVICE_NAME, + version=f"{APP_VERSION}", + description=SERVICE_DESCRIPTION, + routes=app.routes, + ) + app.openapi_schema = openapi_schema + return app.openapi_schema + + +app.openapi = custom_openapi + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--port', type=int, default=9001) + parser.add_argument('--host', type=str, default="0.0.0.0") + parser.add_argument('--reload', action='store_true', default=True) + + args = parser.parse_args() + host = args.host + port = args.port + reload = args.reload + + uvicorn.run('main:app', host=host, port=port, reload=reload)