This document describes the API endpoints, database functions, and edge functions available in the Carpool Network platform.
All API requests require authentication via Supabase Auth. Include the auth token in requests:
const { data, error } = await supabase.auth.getSession();
const token = data.session?.access_token;Creates a ride with atomic transaction guarantees.
const { data, error } = await supabase.rpc('create_atomic_ride', {
p_origin: 'London',
p_destination: 'Manchester',
p_departure_time: '2024-01-15T09:00:00Z',
p_available_seats: 3,
p_price_per_seat: 15.00,
p_vehicle_id: 'uuid',
p_metadata: {}
});Books a ride with seat availability check.
const { data, error } = await supabase.rpc('book_ride_atomic', {
p_ride_id: 'ride-uuid',
p_seats_requested: 2
});Cancels a booking and tracks cancellation history.
const { data, error } = await supabase.rpc('cancel_booking_with_penalty', {
p_booking_id: 'booking-uuid',
p_reason: 'Changed plans'
});Log performance metrics.
const { data, error } = await supabase.rpc('track_performance_metric', {
p_metric_type: 'api_call',
p_metric_name: 'get_rides',
p_value: 123.45,
p_unit: 'ms',
p_endpoint: '/api/rides',
p_metadata: {}
});Get overall system health status.
const { data, error } = await supabase.rpc('get_system_health');
// Returns: {
// overall_status: 'healthy',
// database_status: 'healthy',
// recent_errors: 2,
// avg_response_time_ms: 150.5,
// cache_hit_rate: 85.3,
// active_users: 42
// }Get personalized ride recommendations.
const { data, error } = await supabase.rpc('get_smart_recommendations', {
p_user_id: 'user-uuid',
p_limit: 10
});Get ML-optimized search results.
const { data, error } = await supabase.rpc('optimize_search_results', {
p_user_id: 'user-uuid',
p_origin: 'London',
p_destination: 'Manchester',
p_departure_date: '2024-01-15T09:00:00Z'
});Update user's current location.
const { data, error } = await supabase.rpc('update_live_location', {
p_latitude: 51.5074,
p_longitude: -0.1278,
p_ride_id: 'ride-uuid'
});Queue a notification for a user.
const { data, error } = await supabase.rpc('queue_notification', {
p_user_id: 'user-uuid',
p_type: 'ride_request',
p_title: 'New Ride Request',
p_body: 'Someone wants to join your ride!',
p_data: { ride_id: 'ride-uuid' }
});Mark notification as read.
const { data, error } = await supabase.rpc('mark_notification_read', {
p_notification_id: 'notification-uuid'
});Get count of unread notifications.
const { data, error } = await supabase.rpc('get_unread_notification_count');
// Returns: 5Check if a feature flag is enabled.
const { data, error } = await supabase.rpc('is_feature_enabled', {
p_flag_key: 'new_matching_algorithm'
});
// Returns: true/falseToggle admin status for a user (admin only).
const { data, error } = await supabase.rpc('toggle_admin_status', {
p_user_id: 'user-uuid',
p_is_admin: true
});Validates email addresses using external service.
Endpoint: POST /functions/v1/validate-email
Request:
{
"email": "user@example.com"
}Response:
{
"valid": true,
"disposable": false,
"score": 0.95
}Looks up UK vehicle details by registration.
Endpoint: POST /functions/v1/vehicle-lookup
Request:
{
"registration": "AB12CDE"
}Response:
{
"make": "Ford",
"model": "Focus",
"year": 2020,
"color": "Blue",
"fuel_type": "Petrol"
}Proxies requests to Google Gemini AI API.
Endpoint: POST /functions/v1/gemini-proxy
Request:
{
"prompt": "How can I reduce my carbon footprint?",
"context": "carpooling"
}Response:
{
"response": "Here are some ways to reduce your carbon footprint...",
"confidence": 0.95
}Subscribe to real-time location updates for a ride.
const channel = supabase
.channel('ride_locations_123')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'live_locations',
filter: 'ride_id=eq.ride-uuid'
},
(payload) => {
console.log('Location updated:', payload);
}
)
.subscribe();Subscribe to new messages in a conversation.
const channel = supabase
.channel('messages_456')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'messages',
filter: 'ride_id=eq.ride-uuid'
},
(payload) => {
console.log('New message:', payload);
}
)
.subscribe();Subscribe to notification updates.
const channel = supabase
.channel('notifications')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'notification_history',
filter: `user_id=eq.${userId}`
},
(payload) => {
console.log('New notification:', payload);
}
)
.subscribe();Get all active rides:
const { data, error } = await supabase
.from('rides')
.select('*, driver:profiles(*), vehicle:vehicles(*)')
.eq('status', 'active')
.gte('departure_time', new Date().toISOString())
.order('departure_time', { ascending: true });Create a ride:
const { data, error } = await supabase
.from('rides')
.insert({
origin: 'London',
destination: 'Manchester',
departure_time: '2024-01-15T09:00:00Z',
available_seats: 3,
price_per_seat: 15.00,
vehicle_id: 'vehicle-uuid'
})
.select();Get user's bookings:
const { data, error } = await supabase
.from('bookings')
.select(`
*,
ride:rides(*),
driver:rides(driver:profiles(*))
`)
.eq('passenger_id', userId)
.order('created_at', { ascending: false });Create booking:
const { data, error } = await supabase
.from('bookings')
.insert({
ride_id: 'ride-uuid',
seats_booked: 2,
total_price: 30.00
})
.select();Get profile:
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('id', userId)
.single();Update profile:
const { data, error } = await supabase
.from('profiles')
.update({
full_name: 'John Doe',
bio: 'Love carpooling!',
preferences: {
smoking: false,
pets: true,
music: true
}
})
.eq('id', userId);All API calls should handle errors appropriately:
const { data, error } = await supabase.rpc('some_function');
if (error) {
console.error('API Error:', error);
// Log error
await supabase.rpc('log_error', {
p_error_type: 'api_error',
p_error_message: error.message,
p_severity: 'error'
});
// Show user-friendly message
toast.error('Something went wrong. Please try again.');
return;
}
// Process data
console.log('Success:', data);API requests are rate-limited per user:
- Standard users: 100 requests per minute
- Verified users: 200 requests per minute
- Admin users: Unlimited
Rate limit headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000
- Always handle errors - Never assume API calls will succeed
- Use RPC functions for complex operations requiring transactions
- Batch requests when possible to reduce round trips
- Cache data appropriately to reduce API calls
- Subscribe to real-time for live data instead of polling
- Use select() to only fetch needed columns
- Implement pagination for large datasets
- Log errors for debugging and monitoring
- Validate input before making API calls
- Use TypeScript types for type safety
For API issues or questions:
- Check error logs in admin dashboard
- Review Supabase logs
- Contact support team