bharath/docs/api/API_DESIGN.md
Vivek 394117dd74 BharathTrucks MVP - 6 sprints complete
- Govt-app styled freight marketplace
- Role-based auth (driver/shipper/broker/admin)
- Load board with bidding system
- Trip tracking with status flow
- In-app messaging
- Admin panel
- Mobile bottom nav + PWA
- Docker + Coolify ready
2026-05-31 06:21:13 +00:00

284 lines
7.9 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# BharathTrucks — API Design Document
**Version:** 1.0
**Date:** 2026-05-31
**Base URL:** `https://bharathtrucks.com`
---
## 1. API Architecture
This is a **server-rendered application** (EJS), so most routes return HTML pages. However, some endpoints return JSON for AJAX interactions (bidding, messaging, notifications).
### Route Naming Convention
- Pages: `GET /resource` → renders HTML
- Actions: `POST /resource` → form submission, redirects
- API (JSON): `GET|POST /api/resource` → returns JSON
### Authentication
All protected routes use session middleware. Supabase JWT stored in httpOnly cookie.
---
## 2. Public Routes (No Auth)
| Method | Path | Description | Response |
|--------|------|-------------|----------|
| GET | `/` | Landing page | HTML |
| GET | `/loadboard` | Public load board (read-only) | HTML |
| GET | `/login` | Login page | HTML |
| POST | `/login` | Send OTP | Redirect |
| GET | `/verify-otp` | OTP input page | HTML |
| POST | `/verify-otp` | Verify OTP, create session | Redirect to dashboard |
| GET | `/register` | Registration page | HTML |
| POST | `/register` | Create account + send OTP | Redirect |
| GET | `/about` | About page | HTML |
| GET | `/contact` | Contact page | HTML |
---
## 3. Auth Routes
| Method | Path | Description | Response |
|--------|------|-------------|----------|
| POST | `/auth/send-otp` | Send OTP to phone | JSON `{success, message}` |
| POST | `/auth/verify-otp` | Verify OTP | JSON `{success, redirect}` |
| POST | `/auth/logout` | Destroy session | Redirect to `/` |
| GET | `/auth/onboarding` | Role-specific profile setup | HTML |
| POST | `/auth/onboarding` | Save profile details | Redirect to dashboard |
---
## 4. Load Routes
### Pages
| Method | Path | Description | Auth | Role |
|--------|------|-------------|------|------|
| GET | `/loads` | Load board (authenticated, with filters) | ✅ | All |
| GET | `/loads/new` | Post new load form | ✅ | Shipper, Broker |
| GET | `/loads/:id` | Load detail + bids | ✅ | All |
| GET | `/loads/:id/edit` | Edit load form | ✅ | Owner |
### Actions
| Method | Path | Description | Auth | Role |
|--------|------|-------------|------|------|
| POST | `/loads` | Create new load | ✅ | Shipper, Broker |
| POST | `/loads/:id` | Update load | ✅ | Owner |
| POST | `/loads/:id/cancel` | Cancel load | ✅ | Owner |
### API (JSON)
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/api/loads` | Load list with filters | ✅ |
| GET | `/api/loads/search` | Search by city/route | Optional |
#### Query Parameters for `/api/loads`
```
?origin=Mumbai
&destination=Delhi
&truck_type=open
&min_weight=5
&max_weight=20
&pickup_date=2026-06-01
&status=open
&page=1
&limit=20
```
#### Response Format
```json
{
"success": true,
"data": {
"loads": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 45,
"pages": 3
}
}
}
```
---
## 5. Bid Routes
### Actions
| Method | Path | Description | Auth | Role |
|--------|------|-------------|------|------|
| POST | `/loads/:id/bid` | Place bid on load | ✅ | Driver |
| POST | `/bids/:id/accept` | Accept a bid | ✅ | Load owner |
| POST | `/bids/:id/reject` | Reject a bid | ✅ | Load owner |
| POST | `/bids/:id/withdraw` | Withdraw own bid | ✅ | Bidder |
### API (JSON)
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/api/loads/:id/bids` | Get all bids for a load | ✅ (owner/bidder) |
| GET | `/api/bids/my` | Get my bid history | ✅ |
#### Bid Request Body
```json
{
"amount": 42000,
"estimated_delivery": "2026-06-05",
"note": "Can pick up by evening"
}
```
#### Bid Rate Limiting
- Free users: 5 bids/day → returns `429` with message after limit
- Premium users: unlimited
---
## 6. Dashboard Routes
### Driver
| Method | Path | Description |
|--------|------|-------------|
| GET | `/driver` | Driver dashboard home |
| GET | `/driver/trips` | My trips list |
| GET | `/driver/trips/:id` | Trip detail |
| POST | `/driver/trips/:id/status` | Update trip status |
| GET | `/driver/earnings` | Earnings summary |
| GET | `/driver/profile` | Edit profile/truck |
| POST | `/driver/profile` | Update profile |
| POST | `/driver/availability` | Toggle availability |
### Shipper
| Method | Path | Description |
|--------|------|-------------|
| GET | `/shipper` | Shipper dashboard home |
| GET | `/shipper/loads` | My posted loads |
| GET | `/shipper/shipments` | Active shipments |
| GET | `/shipper/payments` | Payment history |
| POST | `/shipper/rate/:tripId` | Rate a driver |
### Broker
| Method | Path | Description |
|--------|------|-------------|
| GET | `/broker` | Broker dashboard home |
| GET | `/broker/network` | Driver network |
| POST | `/broker/network/add` | Add driver to network |
| GET | `/broker/clients` | Shipper clients |
| GET | `/broker/commissions` | Commission ledger |
| POST | `/broker/commissions/:id/received` | Mark commission received |
| GET | `/broker/loads` | Loads I've posted |
---
## 7. Messaging Routes
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/messages` | Inbox | ✅ |
| GET | `/messages/:userId` | Conversation with user | ✅ |
| POST | `/api/messages` | Send message | ✅ |
| GET | `/api/messages/:userId` | Get conversation (JSON) | ✅ |
| POST | `/api/messages/read/:id` | Mark as read | ✅ |
#### Message Request Body
```json
{
"receiver_id": "uuid",
"load_id": "uuid",
"content": "Is this load still available?"
}
```
---
## 8. Notification Routes
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/api/notifications` | Get unread notifications | ✅ |
| POST | `/api/notifications/read` | Mark all as read | ✅ |
| POST | `/api/notifications/:id/read` | Mark one as read | ✅ |
---
## 9. Admin Routes
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/admin` | Admin dashboard | ✅ Admin |
| GET | `/admin/users` | User management | ✅ Admin |
| POST | `/admin/users/:id/suspend` | Suspend user | ✅ Admin |
| POST | `/admin/users/:id/verify` | Verify user | ✅ Admin |
| GET | `/admin/loads` | All loads | ✅ Admin |
| GET | `/admin/metrics` | Platform metrics | ✅ Admin |
| POST | `/admin/broadcast` | Send announcement | ✅ Admin |
---
## 10. Shared API Patterns
### Success Response
```json
{
"success": true,
"data": { ... },
"message": "Load created successfully"
}
```
### Error Response
```json
{
"success": false,
"error": {
"code": "BID_LIMIT_REACHED",
"message": "Daily bid limit reached. Upgrade to premium for unlimited bids."
}
}
```
### HTTP Status Codes Used
| Code | Meaning |
|------|---------|
| 200 | Success |
| 201 | Created |
| 302 | Redirect (after form submit) |
| 400 | Bad request / validation error |
| 401 | Not authenticated |
| 403 | Not authorized (wrong role) |
| 404 | Not found |
| 429 | Rate limited |
| 500 | Server error |
---
## 11. Middleware Stack
```
Request → Compression → Helmet → Cookie Parser → Session Check
→ Rate Limiter → Role Check → Controller → Response
```
| Middleware | Purpose |
|-----------|---------|
| `compression` | Gzip responses |
| `helmet` | Security headers |
| `cookie-parser` | Parse auth cookies |
| `authMiddleware` | Validate JWT, attach user to req |
| `roleMiddleware(roles)` | Check user role access |
| `rateLimiter` | Global rate limit (100 req/min) |
| `bidLimiter` | Bid-specific limit (5/day free) |
| `errorHandler` | Catch-all error formatting |
---
## 12. WhatsApp Share (No API needed)
Load sharing via `wa.me` links with pre-formatted text:
```
https://wa.me/?text=🚛 New Load Available!%0A📍 Mumbai → Delhi%0A🏋 20 Ton Open Body%0A💰 ₹45,000%0A📅 2 Jun 2026%0A%0AView: https://bharathtrucks.com/loads/abc123
```
---
*All routes follow RESTful conventions. Server-rendered pages for core flows, JSON APIs for dynamic interactions.*