def get_application() -> FastAPI: application = FastAPI(title=config.PROJECT_NAME, debug=config.DEBUG, description=config.API_DESCRIPTION, version=config.VERSION, docs_url=None, redoc_url=None, openapi_url=None) application.add_event_handler("startup", create_start_app_handler(application)) application.add_event_handler("shutdown", create_stop_app_handler(application)) try: application.add_middleware( RequestTracerMiddleware, exporter=AzureExporter( connection_string= f'InstrumentationKey={os.getenv("APPINSIGHTS_INSTRUMENTATIONKEY")}', sampler=ProbabilitySampler(1.0))) except Exception as e: logging.error(f"Failed to add RequestTracerMiddleware: {e}") application.add_middleware(ServerErrorMiddleware, handler=generic_error_handler) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router) return application
def get_application() -> FastAPI: application = FastAPI(title=config.PROJECT_NAME, debug=config.DEBUG, version=config.VERSION) application.add_middleware( CORSMiddleware, allow_origins=config.ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_event_handler( "startup", events.create_startup_app_handler(application)) application.add_event_handler( "shutdown", events.create_shutdown_app_handler(application)) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router, prefix=config.API_PREFIX) return application
def get_application() -> FastAPI: application = FastAPI( title=app_config.PROJECT_NAME, debug=app_config.DEBUG, version=app_config.VERSION, ) application.add_middleware( CORSMiddleware, allow_origins=app_config.ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @application.on_event("startup") async def startup_event(): await connect_to_db() @application.on_event("shutdown") async def shutdown_event(): await close_db_connection() application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router, prefix=app_config.API_PREFIX) return application
def create_app() -> FastAPI: """Creates a FastAPI app. :param: :Config: config_object. app config. """ _logger.info(f"[INFO]: Endpoint Version {api.__version__}") _logger.info(f"[INFO]: config_object is {app_config}") app = FastAPI( title=app_config.INFO["title"], version=api.__version__, description=app_config.INFO["description"], ) # All the API Routers are stored in endpoints.py, so we import them # to the app here. app.include_router(api.endpoints.router) # CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_exception_handler(DataReadingError, data_reading_exception_handler) app.add_exception_handler(DataValidationError, data_validation_exception_handler) _logger.info("FastAPI instance created") return app
def get_application() -> FastAPI: application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION) application.add_middleware( CORSMiddleware, allow_origins=ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.mount("/static", StaticFiles(directory="static"), name="static") application.add_event_handler("startup", create_start_app_handler(application)) application.add_event_handler("shutdown", create_stop_app_handler(application)) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router, prefix=API_PREFIX) application.include_router(html_router, prefix='') return application
def get_application() -> FastAPI: application = FastAPI(title="Haystack-API", debug=True, version="0.1") origins = [ "https://entroprise.com", "https://www.entroprise.com", "https://app.entroprise.com" "https://hasura.entroprise.com", "http://entroprise.com", "http://www.entroprise.com", "http://app.entroprise.com", "http://hasura.entroprise.com", "http://localhost", "http://localhost:3000", "http://127.0.0.1", "http://127.0.0.1:3000", ] application.add_middleware( CORSMiddleware, allow_origin_regex='https?://.*', allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) if APM_SERVER: apm_config = {"SERVICE_NAME": APM_SERVICE_NAME, "SERVER_URL": APM_SERVER, "CAPTURE_BODY": "all"} elasticapm = make_apm_client(apm_config) application.add_middleware(ElasticAPM, client=elasticapm) application.add_exception_handler(HTTPException, http_error_handler) application.include_router(api_router) return application
def get_fastapi_app(title: str = "", debug: bool = False, version: str = "0.0.0"): initial_app = FastAPI(title=title, debug=debug, version=version) initial_app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # App Startup/Shutdown Events initial_app.add_event_handler("startup", create_start_app_handler(initial_app)) initial_app.add_event_handler("shutdown", create_stop_app_handler(initial_app)) # Exception Handlers initial_app.add_exception_handler(HTTPException, http_error_handler) initial_app.add_exception_handler(RequestValidationError, http422_error_handler) # Add Routes initial_app.include_router(api_router, prefix=API_PREFIX) return initial_app
def get_application() -> FastAPI: application = FastAPI() application.add_middleware( CORSMiddleware, allow_origins=ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # application.add_event_handler("startup", create_start_app_handler(application)) # application.add_event_handler("shutdown", create_stop_app_handler(application)) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) # init database models register_tortoise(application, db_url=DATABASE, generate_schemas=True, modules={"models": ["serv.models.images"]}) application.include_router(api_router, prefix=API_PREFIX) return application
def create_app(): app = FastAPI(title="FastAPI Pydiator", description="FastAPI pydiator integration project", version="1.0.0", openapi_url="/openapi.json", docs_url="/", redoc_url="/redoc") app.add_exception_handler(Exception, ExceptionHandlers.unhandled_exception) app.add_exception_handler(DataException, ExceptionHandlers.data_exception) app.add_exception_handler(ServiceException, ExceptionHandlers.service_exception) app.add_exception_handler(HTTPException, ExceptionHandlers.http_exception) app.add_exception_handler(ValidationError, ExceptionHandlers.validation_exception) app.include_router(health_check_resource.router, prefix="/health-check", tags=["health check"]) app.include_router(todo_resource.router, prefix="/v1/todos", tags=["todo"]) @app.on_event('startup') async def startup(): app.add_middleware(StateRequestIDMiddleware) if TRACER_IS_ENABLED: app.state.tracer = tracer app.tracer = app.state.tracer app.add_middleware(OpentracingMiddleware) set_up_pydiator() return app
def get_application(title=__name__, debug=None, version=None): application = FastAPI(title=title, debug=debug, version=version) application.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) async def http_error_handler(_: Request, exc: HTTPException) -> JSONResponse: return JSONResponse({"errors": [exc.detail]}, status_code=exc.status_code) async def http422_error_handler( _: Request, exc: Union[RequestValidationError, ValidationError], ) -> JSONResponse: return JSONResponse( {"errors": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY, ) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) return application
def get_application() -> FastAPI: settings = service_settings() initialize_logging(settings.logging_level) application = FastAPI(**settings.fastapi_kwargs) application.include_router(brain.router) application.include_router(configuration.router) application.include_router(docs.router) application.add_exception_handler( RequestValidationError, validation_error_handler) application.add_exception_handler( LearningHouseException, learninghouse_exception_handler) application.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.mount( '/static', StaticFiles(directory=STATIC_DIRECTORY), name='static') return application
def set_exceptions_handlers(app: FastAPI) -> FastAPI: exceptions_info = {} for exception_class, exception_func in exceptions_info.items(): app.add_exception_handler(exception_class, exception_func) return app
def get_application() -> FastAPI: application = FastAPI(title=settings.PROJECT_NAME, docs_url="/docs", redoc_url='/re-docs', openapi_url=f"{settings.API_PREFIX}/openapi.json", description=''' Base frame with FastAPI micro framework + Postgresql - Login/Register with JWT - Permission - CRUD User - Unit testing with Pytest - Dockerize ''') application.add_middleware( CORSMiddleware, allow_origins=[ str(origin) for origin in settings.BACKEND_CORS_ORIGINS ], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_middleware(DBSessionMiddleware, db_url=settings.DATABASE_URL) application.include_router(router, prefix=settings.API_PREFIX) application.add_exception_handler(CustomException, http_exception_handler) return application
def _init_fastapi_app(): app = FastAPI( title='Imune', description='Imune API', version='0.0.1', redoc_url=None, ) app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) routers = [ user_router, login_router, vaccine_router, person_router, batch_router, vaccinate_router, occurrence_router ] [app.include_router(**r) for r in routers] app.add_event_handler('startup', connect_to_mongo) app.add_event_handler("startup", apply_migrations) app.add_event_handler('shutdown', close_mongo_connection) app.add_exception_handler(NotFoundException, not_found_exception_handler) app.add_exception_handler(BusinessValidationException, business_validation_exception_handler) app.add_exception_handler(ApiBaseException, generic_render) app.add_exception_handler(EnvironmentException, generic_render) app.add_exception_handler(LoginException, generic_render) return app
def get_application(): application = FastAPI(title='FastAPI') application.add_event_handler("startup", create_start_app_handler(application)) application.add_event_handler("shutdown", create_stop_app_handler(application)) application.include_router(api_router, prefix='/api') application.add_exception_handler(HTTPException, http_error_handler) return application
def configure_app(self, app: FastAPI, config): from freqtrade.rpc.api_server.api_auth import http_basic_or_jwt_token, router_login from freqtrade.rpc.api_server.api_backtest import router as api_backtest from freqtrade.rpc.api_server.api_v1 import router as api_v1 from freqtrade.rpc.api_server.api_v1 import router_public as api_v1_public from freqtrade.rpc.api_server.web_ui import router_ui app.include_router(api_v1_public, prefix="/api/v1") app.include_router( api_v1, prefix="/api/v1", dependencies=[Depends(http_basic_or_jwt_token)], ) app.include_router( api_backtest, prefix="/api/v1", dependencies=[Depends(http_basic_or_jwt_token)], ) app.include_router(router_login, prefix="/api/v1", tags=["auth"]) # UI Router MUST be last! app.include_router(router_ui, prefix='') app.add_middleware( CORSMiddleware, allow_origins=config['api_server'].get('CORS_origins', []), allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_exception_handler(RPCException, self.handle_rpc_exception)
def add_exception_handlers(app: FastAPI, status_codes: Dict[Type[Exception], int]) -> None: """ Add exception handlers to the FastAPI app. """ for (exc, code) in status_codes.items(): app.add_exception_handler(exc, exception_handler_factory(code))
def get_application(): tags_metadata = [ { "name": "sms", "description": "Send a omni-channel SMS.", }, { "name": "email", "description": "Semd a omni-channel Email.", }, ] _app = FastAPI( title=settings.PROJECT_NAME, description="Allows government departments to communicate with the citizens through a unified omni-channel communication gateway.", version="v0.0.1", openapi_tags=tags_metadata, ) # setting the limiter here _app.state.limiter = limiter # add graceful exception handling in case ratelimit exceeeds _app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) _app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) return _app
def get_app() -> FastAPI: """ Creates the Fast API application instance :return: The application instance """ settings = get_settings() app = FastAPI( title="LinuxForHealth Connect", description="LinuxForHealth Connectors for Inbound Data Processing", version=__version__, ) app.add_middleware(HTTPSRedirectMiddleware) app.include_router(router) app.add_event_handler("startup", configure_logging) app.add_event_handler("startup", log_configuration) app.add_event_handler("startup", configure_internal_integrations) app.add_event_handler("shutdown", close_internal_clients) app.add_exception_handler(HTTPException, http_exception_handler) # use the slowapi rate limiter app.add_middleware(SlowAPIMiddleware) limiter = Limiter(key_func=get_remote_address, default_limits=[settings.connect_rate_limit]) app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) return app
def add_exception_handlers(app: FastAPI, status_codes: Dict[Type[Exception], int]) -> None: """Add exception handlers to the FastAPI application. Args: app: the FastAPI application. status_codes: mapping between exceptions and status codes. Returns: None """ for (exc, code) in status_codes.items(): app.add_exception_handler(exc, exception_handler_factory(code)) # By default FastAPI will return 422 status codes for invalid requests # But the STAC api spec suggests returning a 400 in this case def request_validation_exception_handler( request: Request, exc: RequestValidationError) -> JSONResponse: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"detail": exc.errors()}, ) app.add_exception_handler(RequestValidationError, request_validation_exception_handler)
def get_application() -> FastAPI: application = FastAPI(title="Haystack-API", debug=True, version="0.1") application.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) if APM_SERVER: apm_config = { "SERVICE_NAME": APM_SERVICE_NAME, "SERVER_URL": APM_SERVER, "CAPTURE_BODY": "all" } elasticapm = make_apm_client(apm_config) application.add_middleware(ElasticAPM, client=elasticapm) application.add_exception_handler(HTTPException, http_error_handler) application.include_router(api_router) return application
def create_application() -> FastAPI: application = FastAPI(title=settings.project_name, debug=settings.debug, version=settings.version) application.add_middleware( CORSMiddleware, allow_origins=settings.allowed_hosts, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @application.on_event("startup") async def startup(): await database.connect() @application.on_event("shutdown") async def shutdown(): await database.disconnect() application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(router, prefix=settings.api_prefix) return application
def get_application() -> FastAPI: settings = get_app_settings() settings.configure_logging() application = FastAPI(**settings.fastapi_kwargs) application.add_middleware( CORSMiddleware, allow_origins=settings.allowed_hosts, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_event_handler( "startup", create_start_app_handler(application, settings), ) application.add_event_handler( "shutdown", create_stop_app_handler(application), ) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router, prefix=settings.api_prefix) return application
def get_app() -> FastAPI: app = FastAPI(title=PROJECT_NAME, version=VERSION, debug=DEBUG) app.add_exception_handler(HTTPException, http_error_handler) app.add_exception_handler(RequestValidationError, http422_error_handler) app.include_router(api_router) return app
def get_application() -> FastAPI: application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) # application.include_router(api_router, prefix=API_PREFIX) # application.add_event_handler("startup", setup_jaeger(application)) return application
def get_application() -> FastAPI: application = FastAPI() application.add_event_handler('startup', start_app_handler(application)) application.add_event_handler('shutdown', stop_app_handler(application)) application.add_exception_handler(ClientError, client_error_handler) application.include_router(router) return application
def _get_app(): from .api.endpoints import router, flow, pod, pea, logs, workspace app = FastAPI( title='JinaD (Daemon)', description='REST interface for managing distributed Jina', version=__version__, openapi_tags=[ { 'name': 'daemon', 'description': 'API to manage the Daemon', }, { 'name': 'flows', 'description': 'API to manage Flows', }, { 'name': 'pods', 'description': 'API to manage Pods', }, { 'name': 'peas', 'description': 'API to manage Peas', }, { 'name': 'logs', 'description': 'API to stream Logs', }, { 'name': 'workspaces', 'description': 'API to manage Workspaces', }, ], ) app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) app.include_router(router) app.include_router(logs.router) app.include_router(pea.router) app.include_router(pod.router) app.include_router(flow.router) app.include_router(workspace.router) app.add_exception_handler(Runtime400Exception, daemon_runtime_exception_handler) return app
def get_application() -> FastAPI: application = FastAPI(title="Haystack-API", debug=True, version="0.1", root_path=ROOT_PATH) # This middleware enables allow all cross-domain requests to the API from a browser. For production # deployments, it could be made more restrictive. application.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_exception_handler(HTTPException, http_error_handler) application.include_router(api_router) return application
def init_app(): title = 'NEOPAY API' application = FastAPI(title=title) # middlwares application.add_middleware(CORSMiddleware, **middlewares.cors_middleware_params) application.add_middleware(LogMiddleware) # set exceptions handler application.add_exception_handler(errors.ApiErrorException, errors.api_error_exception_handler) # urls application.include_router(routing.root_router, prefix='/api') # return return application
def get_application(): application = FastAPI(default_response_class=APIResponse) application.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler( RequestValidationError, http422_error_handler) application.include_router(api_router, prefix="/api") return application