Is there a way to pass query parameter the the last-n endpoint and how do i make it to work in AWS lambda
Below is my code for reference:
import os
import smtplib
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel, Field
from mangum import Mangum
from fastapi.responses import JSONResponse
import mysql.connector
from datetime import datetime
import json
from dbConfig import DBConnector
app = FastAPI()
handler = Mangum(app)
# Define Pydantic model for request body
class UserInteraction(BaseModel):
usr_id: int
usr_info: dict
cpt_dttm: str
interaction_type: str
interaction_detail: str
# Creating Database Object
db_obj = DBConnector(DB_NAME)
@app.get("/")
def read_root():
return JSONResponse({"message": "Welcome to GEM AI Layer API interface"})
# Define FastAPI endpoint for inserting data into the table
@app.post("/user_interactions/")
async def create_user_interaction(user_interaction: UserInteraction):
# Insert data into the table
query = """
INSERT INTO `USER_INTERACTIONS` (`USR_ID`, `USR_INFO`, `CPT_DTTM`, `INTERACTION_TYPE`, `INTERACTION_DETAIL`)
VALUES (%s, %s, %s, %s, %s)
"""
values = (
user_interaction.usr_id,
json.dumps(user_interaction.usr_info),
user_interaction.cpt_dttm,
user_interaction.interaction_type,
user_interaction.interaction_detail
)
db_obj.write(query, values)
return JSONResponse({"message": "User interaction data inserted successfully"})
# FastAPI endpoint for fetching last "n" records
@app.get("/user-interactions/last-n/")
async def get_last_n_user_interactions(n: int = Query(..., gt=0)):
try:
if n > 10:
return JSONResponse({"message": "Input parameter is out of range (keep it below 10)"})
query = "SELECT * FROM USER_INTERACTIONS ORDER BY CPT_DTTM DESC LIMIT "+ str(n)
records = db_obj.read(query)
if records == []:
return JSONResponse({"message": "Empty"})
return {"user_interactions": records}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=5000)
