GenAI – How To Deploy A Python API On An AWS EC2 Instance?
Table Of Contents:
- Introduction.
- Steps To Host React JS App In AWS.
(1) Introduction
Step-1: Connect to the EC2 Instance
Step-2: Navigate To The Project Directory.
- Move to the directory where your Python API code is located:
cd Rahul_R
Step-3: Activate The Created Environment Where Your Dependencies Are Installed.
- Activate the Conda environment where all dependencies are installed:
conda activate smart_search_env
Step-4: Run the API in the Background Using ‘nohup’
- Use
nohupto run the API scripts in the background even after the terminal is closed. Redirect output to a log file for monitoring.
nohup python softline_main.py > softline_main.log &
nohup python hardline_main.py > hardline_main.log &
Step-5: Verify That the APIs Are Running
- To check whether your
softline_main.pyscript is running:
ps ax | grep softline_main\.py
Step-6: Stop or Kill A Running Script
- If you want to stop any running API process, use the
killcommand with the Process ID (PID):
kill -9 <PID>
- Example:
kill -9 51787
- Use this only if the process is misbehaving or needs to be force-stopped.
Step-7: How HardLine.py and SoftLine.py Looks Like
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import List
import uvicorn
app = FastAPI()
# Allow CORS for React frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace with your React app domain for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Dummy in-memory product list for example
products = [
{"id": 1, "name": "Headphone X"},
{"id": 2, "name": "Speaker Y"},
{"id": 3, "name": "Earbud Z"}
]
@app.get("/")
async def health_check():
return {"message": "Hardline API is running!"}
@app.get("/{query}/")
async def search_products(query: str):
results = [p for p in products if query.lower() in p["name"].lower()]
if not results:
raise HTTPException(status_code=404, detail="No products found")
return results
@app.post("/upload_image/")
async def upload_image(file: UploadFile = File(...)):
# Just for demo: In real case, save the file and do image processing
content = await file.read()
file_size = len(content)
# Example dummy response
return [
{"id": 1, "name": "Detected Product A"},
{"id": 2, "name": "Detected Product B"},
{"note": f"File '{file.filename}' uploaded successfully. Size: {file_size} bytes"}
]
# Optional: Catalog endpoint if needed
@app.post("/get_variants/")
async def get_variants(image_url: str):
# Simulate variant retrieval
return {
"variants": [
{"color": "Black", "size": "L"},
{"color": "Red", "size": "M"}
],
"based_on": image_url
}
if __name__ == "__main__":
uvicorn.run("hardline_main:app", host="0.0.0.0", port=8000)

