from fastapi import FastAPI, Request, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from QuoteGenerator import QuoteGenerator from typing import Union from pydantic import BaseModel import time import os # API to key to validate the Referer API_KEY = os.getenv('API_KEY') oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # Function to check of the incoming API call is from valid host or not def api_key_auth(api_key:str = Depends(oauth2_scheme)): if api_key != API_KEY: raise HTTPException( status_code = status.HTTP_401_UNAUTHORIZED, detail="Forbidden Access" ) class QuoteRequest(BaseModel): tags: Union[None, str] app = FastAPI() #Middleware to note time @app.middleware("http") async def note_response_time(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() print(f'Time taken = {process_time-start_time:.1f}s') return response quote_generator = QuoteGenerator() quote_generator.load_generator() @app.post("/", dependencies=[Depends(api_key_auth)]) def root(request: Request): return {"message": "This is the website for quote-generator"} @app.post("/generate_quote", dependencies=[Depends(api_key_auth)]) def generate_quote(req: QuoteRequest): print("Tags: ", req.tags) generated_quote_oup = quote_generator.generate_quote(req.tags) return {'quote': generated_quote_oup}