# Flask API Integration Guide for Next.js ## ๐ Flask API Server Your Flask API server is now ready and running on **`http://localhost:5001`** ### ๐ Available Endpoints | Method | Endpoint | Description | |--------|----------|-------------| | `GET` | `/api/health` | Health check endpoint | | `GET` | `/api/weather?lat=X&lon=Y` | Get weather conditions | | `POST` | `/api/analyze-crashes` | Analyze crash patterns at location | | `POST` | `/api/find-safe-route` | Find safest route between points | | `POST` | `/api/get-single-route` | Get single route with safety analysis | --- ## ๐ฆ Starting the Server ```bash cd /path/to/VTHacks13/llm python api/flask_server.py ``` The server will start on `http://localhost:5001` with the following services: - โ MongoDB connection to crash database - โ Route safety analysis - โ Weather API integration (Open-Meteo) - โ Gemini AI for safety recommendations --- ## ๐ง Next.js Integration ### 1. Install Dependencies ```bash npm install axios # or use fetch API ``` ### 2. Create API Client Create `lib/api-client.js`: ```javascript const API_BASE_URL = 'http://localhost:5001/api'; // Health Check export async function checkAPIHealth() { const response = await fetch(`${API_BASE_URL}/health`); return response.json(); } // Weather API export async function getWeather(lat, lon) { const response = await fetch(`${API_BASE_URL}/weather?lat=${lat}&lon=${lon}`); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Failed to fetch weather'); } return data; } // Crash Analysis export async function analyzeCrashes(lat, lon, radius = 1.0) { const response = await fetch(`${API_BASE_URL}/analyze-crashes`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ lat, lon, radius }) }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Failed to analyze crashes'); } return data; } // Safe Route Finding export async function findSafeRoute(startLat, startLon, endLat, endLon) { const response = await fetch(`${API_BASE_URL}/find-safe-route`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ start_lat: startLat, start_lon: startLon, end_lat: endLat, end_lon: endLon }) }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Failed to find safe route'); } return data; } // Single Route export async function getSingleRoute(startLat, startLon, endLat, endLon, profile = 'driving') { const response = await fetch(`${API_BASE_URL}/get-single-route`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ start_lat: startLat, start_lon: startLon, end_lat: endLat, end_lon: endLon, profile }) }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Failed to get route'); } return data; } ``` ### 3. Example React Component Create `components/SafetyAnalysis.jsx`: ```jsx import { useState } from 'react'; import { analyzeCrashes, findSafeRoute, getWeather } from '../lib/api-client'; export default function SafetyAnalysis() { const [loading, setLoading] = useState(false); const [results, setResults] = useState(null); const [error, setError] = useState(null); const handleAnalyze = async () => { setLoading(true); setError(null); try { // Example: Analyze crashes around Virginia Tech const lat = 37.2284; const lon = -80.4234; const radius = 2.0; // Get crash analysis const crashData = await analyzeCrashes(lat, lon, radius); // Get safe route (Virginia Tech to Downtown Blacksburg) const routeData = await findSafeRoute(lat, lon, 37.2297, -80.4139); // Get weather const weatherData = await getWeather(lat, lon); setResults({ crashes: crashData, route: routeData, weather: weatherData }); } catch (err) { setError(err.message); } finally { setLoading(false); } }; return (
Total crashes: {results.crashes.crash_summary.total_crashes}
Total casualties: {results.crashes.crash_summary.total_casualties}
Weather: {results.crashes.weather.summary}
Distance: {results.route.recommended_route.distance_km.toFixed(1)} km
Duration: {results.route.recommended_route.duration_min.toFixed(0)} minutes
Crashes nearby: {results.route.recommended_route.crashes_nearby}
Safety score: {results.route.recommended_route.safety_score.toFixed(3)}
{results.weather.summary}