Here's the Svelte server (these will be slightly different now that NPM is insalled outside the venv):
```
(newsHack) ethan@ethan-desktop:~/PycharmProjects/newsHack/frontend$ npm run dev --host --port 3333
>
[email protected] dev
> vite dev --host --port 3333
Port 3333 is in use, trying another one...
Port 3334 is in use, trying another one...
Port 3335 is in use, trying another one...
Port 3336 is in use, trying another one...
Port 3337 is in use, trying another one...
VITE v5.4.11 ready in 644 ms
➜ Local: http://localhost:3338/
➜ Network: http://192.168.1.217:3338/
➜ Network: http://192.168.1.173:3338/
```
This is the API endpoint defined in the backend:
```
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from backend.infrastructure.external_services.gdelt.gdelt_context_service import GDELTService
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
gdelt_service = GDELTService()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace '*' with specific origins for security
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class QueryRequest(BaseModel):
search_query: str
@app.post("/find-microtrend")
def find_microtrend(request: QueryRequest):
try:
articles_dict, stats, narrative, microtrend = gdelt_service.find_gdelt_microtrend(
user_query=request.search_query
)
return {
"articles": articles_dict,
"stats": stats,
"narrative": narrative,
"microtrend": microtrend
}
except Exception as e:
return JSONResponse(
status_code=500,
content={"error": f"An error occurred: {str(e)}"},
)
```
Here's the API startup:
```
(newsHack) ethan@ethan-desktop:~/PycharmProjects/newsHack$ uvicorn backend.interfaces.api.gdelt_query_fast_api:app --host 0.0.0.0 --port 8000 --reload
INFO: Will watch for changes in these directories: ['/home/ethan/PycharmProjects/newsHack']
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started reloader process [83603] using StatReload
INFO: Started server process [83605]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
Here's the API call in the Svelte page:
```
<script>
import TruncatedText from './TruncatedText.svelte';
let searchQuery = '';
let isTyping = false;
let isLoading = false;
let errorMessage = '';
let responseData = null;
let searchHistory = [];
async function handleSubmit() {
errorMessage = '';
isLoading = true;
try {
const response = await fetch('http://localhost:8000/find-microtrend', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ search_query: searchQuery })
});
```