mominah commited on
Commit
06e839f
·
verified ·
1 Parent(s): 97869ef

Create contact.py

Browse files
Files changed (1) hide show
  1. contact.py +41 -0
contact.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # === contact.py ===
2
+ # Create this new file at the project root or in your routers directory
3
+ from datetime import datetime
4
+ from fastapi import APIRouter, HTTPException, status
5
+ from pymongo.collection import Collection
6
+
7
+ from config import CONNECTION_STRING
8
+ from pymongo import MongoClient
9
+ from models import ContactMessage
10
+
11
+ # Initialize MongoDB client and collection
12
+ _client = MongoClient(CONNECTION_STRING)
13
+ _db = _client.users_database
14
+ messages_collection: Collection = _db.get_collection("messages")
15
+
16
+ router = APIRouter(prefix="/contact", tags=["contact"])
17
+
18
+ @router.post(
19
+ "/",
20
+ status_code=status.HTTP_201_CREATED,
21
+ response_model=dict,
22
+ summary="Submit a contact message"
23
+ )
24
+ async def submit_contact(contact: ContactMessage):
25
+ """
26
+ Receive first_name, last_name, email, and message in the request body
27
+ and store them in MongoDB.
28
+ """
29
+ doc = contact.dict()
30
+ doc.update({"created_at": datetime.utcnow()})
31
+
32
+ try:
33
+ result = messages_collection.insert_one(doc)
34
+ except Exception as e:
35
+ raise HTTPException(
36
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
37
+ detail="Failed to save contact message"
38
+ )
39
+
40
+ return {"message": "Contact message received", "id": str(result.inserted_id)}
41
+