KamalamSivakumar's picture
Update app.py
c8ffb23 verified
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google.auth.transport.requests import Request as GoogleRequest
import os
import logging
app = FastAPI()
# CORS settings (update with your frontends if needed)
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Schema for incoming request
class EventDetails(BaseModel):
summary: str
location: str | None = ''
description: str | None = ''
attendees: list[dict] | None = []
start: str # ISO format datetime
end: str # ISO format datetime
timeZone: str | None = 'Asia/Kolkata'
@app.get("/")
async def root():
return {"message": "FastAPI Google Calendar Scheduler is running!"}
@app.post("/schedule")
async def schedule_event(event_details: EventDetails):
SCOPES = ['https://www.googleapis.com/auth/calendar']
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(GoogleRequest())
else:
return {
"status": "error",
"message": "Missing or invalid token. Please run locally to generate token.json."
}
try:
service = build('calendar', 'v3', credentials=creds)
event = {
'summary': event_details.summary,
'location': event_details.location,
'description': event_details.description,
'attendees': event_details.attendees,
'start': {
'dateTime': event_details.start,
'timeZone': event_details.timeZone,
},
'end': {
'dateTime': event_details.end,
'timeZone': event_details.timeZone,
},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
created_event = service.events().insert(calendarId='primary', body=event, sendUpdates='all').execute()
return {
"status": "success",
"event_link": created_event.get('htmlLink'),
"message": f"Event created: {created_event.get('summary')}"
}
except Exception as e:
return {
"status": "error",
"message": str(e)
}