-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
109 lines (96 loc) · 4.17 KB
/
main.py
File metadata and controls
109 lines (96 loc) · 4.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from fastapi import FastAPI, HTTPException, Depends, Header, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pymongo import MongoClient
from contextlib import asynccontextmanager
import os
import stripe
import logging
# --- Configuration ---
MONGODB_URI = os.getenv("MONGODB_URI", "mongodb+srv://<topboybrooks1_db_user>:<6M6mdxRk7BYbyhIG>@apimicrosaas.kwtxluh.mongodb.net/?retryWrites=true&w=majority&appName=APImicrosaas")
STRIPE_API_KEY = os.getenv("STRIPE_API_KEY")
stripe.api_key = STRIPE_API_KEY
# --- Lifespan Events ---
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: Connect to DB
app.mongodb_client = MongoClient(MONGODB_URI)
app.database = app.mongodb_client.get_database("devtools_conglomerate")
logging.info("Connected to MongoDB")
yield
# Shutdown: Close DB connection
app.mongodb_client.close()
logging.info("Disconnected from MongoDB")
# --- FastAPI App Initialization ---
app = FastAPI(lifespan=lifespan, title="DevTools Conglomerate API Template", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# --- Dependency: Get API Key from Header ---
async def get_api_key(x_api_key: str = Header(None)):
if not x_api_key:
raise HTTPException(status_code=401, detail="Missing API Key")
# Check if key exists and is active in MongoDB
key_doc = app.database.api_keys.find_one({"key": x_api_key, "is_active": True})
if not key_doc:
raise HTTPException(status_code=401, detail="Invalid API Key")
return key_doc
# --- Generic Health Check Endpoint (for all APIs) ---
@app.get("/", tags=["TEST-DATA-API "])
async def root():
return {"message": "DevTools Conglomerate API is operational", "status": "success"}
# --- Stripe Webhook Handler (for all APIs) ---
@app.post("/stripe-webhook", tags=["TEST-DATA-API "])
async def stripe_webhook(request: Request):
payload = await request.body()
sig_header = request.headers.get('stripe-signature')
try:
event = stripe.Webhook.construct_event(
payload, sig_header, os.getenv('STRIPE_WEBHOOK_SECRET')
)
except ValueError as e:
raise HTTPException(status_code=400, detail="Invalid payload")
except stripe.error.SignatureVerificationError as e:
raise HTTPException(status_code=400, detail="Invalid signature")
# Handle the event (e.g., subscription created, payment succeeded)
# This will update the user's tier in MongoDB
# Placeholder for logic
return JSONResponse(status_code=200, content={"status": "success"})
# --- Test Data Fabricator API Logic ---
from faker import Faker
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import json
fake = Faker()
class DataGenerationRequest(BaseModel):
schema_definition: Dict[str, Any] # e.g., {"name": "first_name", "email": "email", "address": {"city": "city", "zipcode": "zipcode"}}
n: int = 1 # number of records to generate
@app.post("/generate", tags=["TEST-DATA-API "])
async def generate_test_data(request: DataGenerationRequest, api_key_info: dict = Depends(get_api_key)):
"""
Generate realistic test data based on a user-provided schema.
"""
def generate_item(schema):
item = {}
for key, value_type in schema.items():
if isinstance(value_type, dict):
# Nested object
item[key] = generate_item(value_type)
else:
# Map the string to a Faker method
try:
# Get the Faker method (e.g., "first_name")
method = getattr(fake, value_type)
item[key] = method()
except AttributeError:
# If the method doesn't exist, just use the string itself
item[key] = f"Unknown type: {value_type}"
return item
try:
data = [generate_item(request.schema_definition) for _ in range(request.n)]
return {"status": "success", "data": data, "generated": request.n}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating data: {str(e)}")