Sign in with Google

Gomi API v1.0

Waste collection management platform β€” driver tracking, dispatch, and administration.

Base URL https://getgomi.xyz
The complete reference
This page walks through the main flows. Every endpoint, with its fields and errors as the server has them, is in /api/docs.md: where this page and it differ, /api/docs.md is right.
Driver Dispatch Admin Public

Quick Start

Get up and running with the Gomi API in minutes. All endpoints return JSON. A script or app sends a JWT or an API key in an Authorization header; the console's pages use their session cookie.

Required Headers

A request from a script or app sends these headers:

HTTP Headers
Authorization: Bearer <your-jwt-token-or-api-key>
Content-Type: application/json
Auth Methods β€” Which Token To Use
MethodToken FormatAccess LevelUse Case
JWTeyJhbGciOi... (long base64)βœ… All endpointsMobile apps, SPAs
API Keygomi_d0ea77fe... (starts with gomi_)⚠️ /api/driver/*, /auth/me and /api/me/companies onlyThe driver app, driver scripts

Both go in the same header: Authorization: Bearer <token>

API Client Helper (React Native / JavaScript)

JavaScript
const BASE = 'https://getgomi.xyz';

// Store the JWT after login (see Mobile App Flow below)
let jwtToken = null;

async function api(path, opts = {}) {
  const res = await fetch(BASE + path, {
    ...opts,
    headers: {
      'Authorization': `Bearer ${jwtToken}`,
      'Content-Type': 'application/json',
      ...opts.headers,
    },
  });
  if (res.status === 401) {
    // Token expired β€” try refreshing
    const refreshed = await refreshToken();
    if (refreshed) return api(path, opts); // retry once
    throw new Error('Session expired, please log in again');
  }
  if (!res.ok) {
    const e = await res.json().catch(() => ({}));
    throw new Error(e.error || res.statusText);
  }
  return res.json();
}

async function refreshToken() {
  try {
    const res = await fetch(BASE + '/auth/refresh', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${jwtToken}`,
        'Content-Type': 'application/json',
      },
    });
    if (!res.ok) return false;
    const data = await res.json();
    jwtToken = data.token; // save new token
    return true;
  } catch {
    return false;
  }
}

Usage Examples

JavaScript
// Get current user
const { user } = await api('/auth/me');

// Clock in as driver
await api('/api/driver/clock-in', {
  method: 'PUT',
  body: JSON.stringify({ latitude: 35.68, longitude: 139.77 }),
});

// Fetch assigned jobs
const { jobs } = await api('/api/driver/jobs?status=assigned');

// Start a trip
const { trip } = await api('/api/driver/trips/start', {
  method: 'POST',
  body: JSON.stringify({ job_id: 'job-uuid', latitude: 35.68, longitude: 139.77 }),
});

cURL Examples

Bash
# With JWT token
curl -H "Authorization: Bearer eyJhbGciOi..." \
     https://getgomi.xyz/auth/me

# With API key (driver endpoints only)
curl -H "Authorization: Bearer gomi_d0ea77fe..." \
     https://getgomi.xyz/api/driver/jobs

# POST with JSON body
curl -X PUT \
  -H "Authorization: Bearer eyJhbGciOi..." \
  -H "Content-Type: application/json" \
  -d '{"latitude": -1.286, "longitude": 36.817}' \
  https://getgomi.xyz/api/driver/clock-in

Authentication

Gomi uses Google OAuth 2.0 for login. The API supports three auth methods, all sent via the same Authorization: Bearer <token> header.

Auth Tiers

TierHow You Get ItExpiresEndpoint Access
JWTPOST /auth/token (exchange session cookie)24 hoursAll endpoints
Session CookieSet automatically after Google OAuth login30 daysAll endpoints (browser only)
API KeyPOST /api/keys, an admin's New key, or the first POST /auth/tokenConfigurable/api/driver/*, /auth/me, /api/me/companies, /auth/logout
⚠️ API Key Limitations
API keys reach only the driver API (/api/driver/*), plus /auth/me, /api/me/companies and /auth/logout. Every other endpoint (profile, keys, dispatch, admin, super admin, the live stream) needs a JWT or a session, and answers a key with 403. This limits what a lost key can do. A key acts only in the company it was made in.

Company context: X-Company-ID

A late addition
X-Company-ID was a late addition to the API, and the endpoints it applies to did not document it until November 2026.

A user can belong to more than 1 company (a driver can drive for 2). Every request acts in 1 of them, with the user's role in that company, picked in this order:

#SourceNotes
1X-Company-ID: <company id> headerMust be a company the user belongs to; any other gives the request no company (and no role)
2gomi_company cookieBrowser page loads; a company the user has left falls through to 3
3NeitherThe user's first company by name, which for a driver of 2 companies need not be the company of the job in hand

An API key acts in its own company only. GET /api/me/companies lists the user's companies, and a job's company is job.company_id in GET /api/driver/jobs/{id}.

Driver callsX-Company-ID
The route job calls: POST /api/driver/trips/start, GET /api/driver/trips?job_id=, POST /api/driver/jobs/{id}/stops/{stopId}, /api/driver/trips/{id} and its /photosNot needed: they answer for a job assigned to the driver, in any company
The collection point photo calls: GET /api/driver/collection-points/{id}/photos, .../photo-gallery, .../job-photos and GET /api/driver/jobs/{id}/collection-point-photosNot needed: they answer for a point in any company the driver belongs to (until November 2026 they answered only for the company the request acts in: 404 "collection point not found" or 403 "collection point not in your company" otherwise)
GET /api/driver/nearby-jobsLists the jobs of the company the request acts in only: send X-Company-ID to pick it
POST /api/driver/jobs/{id}/photosNeeded: the job's company. For pickup photos use POST /api/driver/trips/{stop id}/photos, which does not need it

πŸ“± Mobile App Login Flow (React Native)

This is the recommended flow for mobile apps. Open Google OAuth in a WebView, extract the session cookie, exchange it for a JWT, then use the JWT for all subsequent API calls.

1. Open WebView
/auth/login
β†’ 2. User signs in
Google OAuth
β†’ 3. Cookie set
gomi_session
β†’ 4. Exchange for JWT
POST /auth/token
β†’ 5. Use JWT
Authorization: Bearer <jwt>
React Native β€” Complete Login Flow
import { WebView } from 'react-native-webview';
import AsyncStorage from '@react-native-async-storage/async-storage';
import CookieManager from '@react-native-cookies/cookies';

const BASE = 'https://getgomi.xyz';

// Step 1-3: Open WebView for Google OAuth login
function LoginScreen({ onLoginSuccess }) {
  const handleNavigationChange = async (navState) => {
    // After OAuth callback, the URL returns to the app
    // and the session cookie "gomi_session" is now set
    if (navState.url.includes('/welcome') || navState.url === BASE + '/') {
      // Step 4: Exchange the session cookie for a JWT
      const cookies = await CookieManager.get(BASE);
      const sessionCookie = cookies.gomi_session?.value;

      if (sessionCookie) {
        const res = await fetch(`${BASE}/auth/token`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Cookie': `gomi_session=${sessionCookie}`,
          },
        });
        const data = await res.json();
        // data = { token: "eyJhbG...", expires_in: 86400, token_type: "Bearer",
        //          api_key: "gomi_..." (first login only) }

        // Step 5: Store JWT for all future API calls
        await AsyncStorage.setItem('jwt_token', data.token);
        await AsyncStorage.setItem('jwt_expires_at',
          String(Date.now() + data.expires_in * 1000));

        // Store auto-provisioned API key (first login only)
        if (data.api_key) {
          await AsyncStorage.setItem('api_key', data.api_key);
        }

        onLoginSuccess(data.token);
      }
    }
  };

  return (
    <WebView
      source={{ uri: `${BASE}/auth/login` }}
      onNavigationStateChange={handleNavigationChange}
      sharedCookiesEnabled={true}
    />
  );
}

// Step 5: Use JWT for all API calls
async function api(path, opts = {}) {
  let token = await AsyncStorage.getItem('jwt_token');
  const expiresAt = await AsyncStorage.getItem('jwt_expires_at');

  // Auto-refresh if expiring within 1 hour
  if (expiresAt && Date.now() > Number(expiresAt) - 3600000) {
    token = await doRefresh(token);
  }

  const res = await fetch(BASE + path, {
    ...opts,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      ...opts.headers,
    },
  });
  if (!res.ok) {
    const e = await res.json().catch(() => ({}));
    throw new Error(e.error || res.statusText);
  }
  return res.json();
}

async function doRefresh(currentToken) {
  const res = await fetch(`${BASE}/auth/refresh`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${currentToken}`,
      'Content-Type': 'application/json',
    },
  });
  if (!res.ok) throw new Error('Token refresh failed β€” re-login required');
  const data = await res.json();
  await AsyncStorage.setItem('jwt_token', data.token);
  await AsyncStorage.setItem('jwt_expires_at',
    String(Date.now() + data.expires_in * 1000));
  return data.token;
}

Auth Endpoints

GET /auth/login Redirect to Google OAuth β–Ύ

Redirects the user to Google's OAuth consent screen. After authorization, the user is redirected back with a gomi_session cookie set (30-day expiry, HttpOnly, Secure).

Note
Open this URL in a browser or WebView β€” do not call via fetch/AJAX.
Query Parameters
ParamTypeDescription
redirectstringOptional URL to redirect after login (default: welcome page)
POST /auth/token Exchange session cookie β†’ JWT β–Ύ

Exchanges a valid session cookie for a JWT. This is the key step for mobile apps β€” call this right after the OAuth WebView flow completes.

πŸ“± Mobile apps β€” this is your most important endpoint
After Google login sets the gomi_session cookie, call this endpoint with that cookie to get a JWT. Store the JWT and use it for all subsequent API calls.

Auto-provisioned API key: On the first call, if the user has no API key yet, one is automatically created and returned in the api_key field. Save it β€” it’s only shown once. Use the JWT for all endpoints; the API key is a fallback for /api/driver/* only.
Request
HTTP
POST /auth/token HTTP/1.1
Host: getgomi.xyz
Cookie: gomi_session=<session-id-from-oauth-login>
Content-Type: application/json

No request body needed.

Response β€” 200 OK
JSON
// First call (no API key yet β€” one is auto-created):
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYzg4...",
  "expires_in": 86400,
  "token_type": "Bearer",
  "api_key": "gomi_a1b2c3d4e5f6...",
  "api_key_note": "Auto-generated API key for /api/driver/* endpoints. Save it β€” it won't be shown again."
}

// Subsequent calls (user already has key):
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYzg4...",
  "expires_in": 86400,
  "token_type": "Bearer"
}
Fields
FieldTypeDescription
tokenstringJWT token β€” use this in Authorization: Bearer <token>
expires_inintSeconds until expiry (86400 = 24 hours)
token_typestringAlways "Bearer"
api_keystring?Only present on first call if user had no key. Raw API key for /api/driver/*. Save it β€” never shown again.
api_key_notestring?Explanation (present only when api_key is included)
Error Responses
StatusBodyMeaning
401{"error": "not authenticated"}No valid session cookie
403{"error": "session or JWT authentication required"}API key auth used (not allowed β€” must use session cookie)
POST /auth/refresh Refresh an expiring JWT β–Ύ

Exchanges a still-valid JWT for a fresh one with a new 24-hour expiry. Call this before the current token expires to keep the user logged in without re-doing OAuth.

Request
HTTP
POST /auth/refresh HTTP/1.1
Host: getgomi.xyz
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Content-Type: application/json

No request body needed. Must use a JWT (not a session cookie or API key).

Response β€” 200 OK
JSON
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vy...",
  "expires_in": 86400,
  "token_type": "Bearer"
}
Error Responses
StatusBodyMeaning
401{"error": "not authenticated"}No token or token expired
403{"error": "JWT required for refresh"}Used session/API key instead of JWT
πŸ’‘ Tip
Refresh proactively when there's <1 hour left (check expires_in). If refresh fails, redirect the user back to the login WebView.
GET /auth/me Get current user β–Ύ

Returns the currently authenticated user's profile. Use this to verify the token works and get user info after login.

Request
HTTP
GET /auth/me HTTP/1.1
Host: getgomi.xyz
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Response β€” 200 OK
JSON
{
  "user": {
    "id": "c88d57e3b2c5a460e194c5a398a26b2c",
    "email": "driver@example.com",
    "first_name": "Harold",
    "last_name": "M",
    "avatar_url": "https://lh3.googleusercontent.com/...",
    "role": "driver",
    "status": "offline"
  }
}
POST /auth/logout End session β–Ύ

Destroys the server-side session and clears the gomi_session cookie. JWTs already issued will remain valid until they expire (24h), but new token exchanges will fail.

Response β€” 200 OK
JSON
{
  "message": "logged out"
}

API Keys

API keys provide simple auth for driver endpoints. They work on the driver API (/api/driver/*) and on /auth/me, /api/me/companies and /auth/logout. For anything else, use a JWT (see above). A person has at most 10 active keys.

How to send an API key

Use the same Authorization header β€” or a query parameter as a fallback:

Authorization: Bearer gomi_d0ea77fefcf5f813...

# OR as query parameter:
GET /api/driver/jobs?key=gomi_d0ea77fefcf5f813...
POST /api/keys Create API key β–Ύ

Requires JWT or session cookie auth (API key auth cannot create new keys).

⚠️ Important
The raw key value is returned only once. Store it securely immediately.
Request Body
JSON
{
  "name": "phone",
  "expires_in": "90d"
}
Response β€” 201 Created
JSON
{
  "key": "gomi_3f9a...(64 hex)",
  "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
  "name": "phone",
  "prefix": "gomi_3f9a1c2b",
  "expires": "2026-07-01T00:00:00Z",
  "message": "Save this key now. It will not be shown again."
}
GET /api/keys List your API keys β–Ύ
Response β€” 200 OK
JSON
{
  "keys": [
    {
      "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
      "user_id": "usr_d001",
      "name": "phone",
      "key_prefix": "gomi_3f9a1c2b",
      "created_at": "2026-04-01T00:00:00Z",
      "expires_at": "2026-07-01T00:00:00Z",
      "last_used_at": "2026-04-14T03:22:00Z",
      "revoked": 0
    }
  ]
}
DELETE /api/keys/{id} Revoke an API key β–Ύ

Permanently revokes one of your own keys. Any requests using this key will immediately fail with 401. Any other id: 404 "key not found".

Response β€” 200 OK
JSON
{
  "message": "key revoked"
}

Profile

Manage the authenticated user's own profile. Requires JWT or session cookie. Auth Required

GET /api/profile Get your profile β–Ύ

Returns the full profile of the authenticated user including location and timestamps.

Response β€” 200 OK
JSON
{
  "user": {
    "id": "c88d57e3...",
    "email": "driver@example.com",
    "first_name": "Harold",
    "last_name": "M",
    "avatar_url": "https://lh3.googleusercontent.com/...",
    "role": "driver",
    "status": "online",
    "last_known_lat": -1.286,
    "last_known_lng": 36.817,
    "created_at": "2026-06-01T00:00:00Z"
  }
}
PUT /api/profile Update your profile β–Ύ
Request Body
JSON
{
  "first_name": "Harold",
  "last_name": "Mukuru"
}
Response β€” 200 OK
JSON
{
  "user": { ... },
  "message": "profile updated"
}

Driver: Shifts & Location

Drivers must clock in before accepting jobs. Location updates keep the dispatch dashboard current. Driver

PUT /api/driver/clock-in Start shift β–Ύ

Clocks the driver in and sets their status to online. Requires current GPS coordinates.

Request Body
JSON
{
  "latitude": 35.6812,
  "longitude": 139.7671
}
Response β€” 200 OK
JSON
{
  "user": {
    "id": "driver-uuid",
    "status": "online",
    "latitude": 35.6812,
    "longitude": 139.7671
  },
  "message": "clocked in"
}
PUT /api/driver/clock-out End shift β–Ύ
Request Body
JSON
{
  "notes": "Finished all scheduled routes"
}
Response β€” 200 OK
JSON
{
  "user": { "id": "driver-uuid", "status": "offline" },
  "message": "clocked out"
}
PUT /api/driver/location Update location β–Ύ

Pushes a background location update outside of active trips. Use this while online but not on an active trip.

Request Body
JSON
{
  "latitude": 35.6812,
  "longitude": 139.7671
}
GET /api/driver/dashboard Driver overview β–Ύ

Returns the driver's current status, active shift, and job summary.

Response β€” 200 OK
JSON
{
  "user": { "id": "driver-uuid", "first_name": "Tanaka", "status": "online" },
  "status": "online",
  "active_shift": {
    "clocked_in_at": "2026-04-14T08:00:00Z",
    "latitude": 35.6812,
    "longitude": 139.7671
  },
  "active_jobs": [],
  "upcoming_jobs": [
    { "id": "job-1", "title": "Shibuya pickup", "status": "assigned" }
  ],
  "stats": {
    "active": 0,
    "upcoming": 1,
    "completed_today": 5,
    "total": 142
  }
}
GET /api/driver/shifts Shift history β–Ύ

Returns the driver's shift event history (clock-in / clock-out pairs). Filter by date range.

Query Parameters
ParamTypeDescription
fromstringStart date (RFC 3339 or YYYY-MM-DD)
tostringEnd date (RFC 3339 or YYYY-MM-DD)
Response β€” 200 OK
JSON
{
  "events": [
    {
      "id": "evt-uuid-001",
      "type": "clock_in",
      "latitude": 35.6812,
      "longitude": 139.7671,
      "created_at": "2026-01-15T08:00:00Z"
    },
    {
      "id": "evt-uuid-002",
      "type": "clock_out",
      "notes": "End of shift",
      "created_at": "2026-01-15T17:00:00Z"
    }
  ]
}
PUT /api/driver/status Set availability β–Ύ

Set the driver's availability status without a full clock-in/clock-out cycle.

Request Body
JSON
{
  "status": "online"
}

Accepted values: online, offline.

Response β€” 200 OK
JSON
{
  "user": {
    "id": "driver-uuid",
    "status": "online",
    "first_name": "Tanaka",
    "last_name": "Yuki"
  },
  "message": "status updated"
}
GET /api/driver/nearby-jobs Find nearby unassigned jobs β–Ύ

Returns unassigned jobs near the driver's current location. The driver must be online with a known location.

Query Parameters
ParamTypeDescription
limitintMax results (default 10)
Response β€” 200 OK
JSON
{
  "jobs": [
    {
      "id": "job-uuid-010",
      "title": "Shibuya Ward - Burnable",
      "address": "1-2-3 Shibuya, Shibuya-ku, Tokyo",
      "latitude": 35.6580,
      "longitude": 139.7016,
      "distance_km": 1.3,
      "priority": "normal",
      "waste_type": "Burnable",
      "scheduled_date": "2026-04-15"
    }
  ]
}

Driver: Jobs

View and manage assigned collection jobs. Driver

GET /api/driver/jobs List jobs β–Ύ
Query Parameters
ParamTypeDescription
statusstringFilter: assigned, in_progress, completed, pending
limitintMax results (default 50)
offsetintPagination offset
Response β€” 200 OK
JSON
{
  "jobs": [
    {
      "id": "job-uuid-001",
      "title": "Shibuya Ward - Burnable",
      "address": "1-2-3 Shibuya, Shibuya-ku, Tokyo",
      "latitude": 35.6580,
      "longitude": 139.7016,
      "status": "assigned",
      "priority": "normal",
      "waste_type_name": "Burnable",
      "waste_type_icon": "πŸ”₯"
    }
  ],
  "total": 1
}
GET /api/driver/jobs/{id} Get job detail β–Ύ
Response β€” 200 OK
JSON
{
  "job": {
    "id": "job-uuid-001",
    "title": "Shibuya Ward - Burnable",
    "address": "1-2-3 Shibuya, Shibuya-ku, Tokyo",
    "latitude": 35.6580,
    "longitude": 139.7016,
    "status": "assigned",
    "priority": "normal",
    "scheduled_date": "2026-04-14",
    "estimated_volume": 2.5,
    "waste_type_name": "Burnable",
    "waste_type_icon": "πŸ”₯",
    "notes": "Gate code: 1234",
    "assigned_at": "2026-04-14T07:00:00Z"
  }
}
POST /api/driver/jobs/{id}/start Start a job β–Ύ
Request Body
JSON
{
  "latitude": 35.6812,
  "longitude": 139.7671
}
Response β€” 200 OK
JSON
{
  "job": { "id": "job-uuid-001", "status": "in_progress" },
  "message": "job started"
}
POST /api/driver/jobs/{id}/complete Complete a job β–Ύ
Request Body
JSON
{
  "notes": "Collected 3 bags from front gate",
  "actual_volume": 3.0
}
Response β€” 200 OK
JSON
{
  "job": { "id": "job-uuid-001", "status": "completed" },
  "message": "job completed",
  "status": "completed"
}
POST /api/driver/jobs/{id}/stops/{stopId} Set the status of 1 stop of a route job β–Ύ

stopId is the stop's id in GET /api/driver/trips?job_id={id}. The job must be open and assigned to the caller, or in the company they act in. arrived_at is kept from the first arrival; completed_at is set when the stop is completed or cancelled. 400 for an unknown status, 404 for a stop not on the job, 409 for a closed job.

Request Body
JSON
{
  "status": "completed"
}
Response β€” 200 OK
JSON
{
  "stop": {
    "id": "c7beb500bdd949fea91a7832d7b813bf",
    "job_id": "job-uuid-001",
    "collection_point_id": "cp-uuid-002",
    "stop_order": 1,
    "status": "completed",
    "arrived_at": "2026-10-29T15:51:28Z",
    "completed_at": "2026-10-29T15:58:02Z"
  }
}
POST /api/driver/jobs/{id}/abort Abort job (cancels active trip if en route) β–Ύ
Scenario

Driver encounters an emergency (car accident, equipment malfunction, blocked road, etc.) while assigned to a job or en route to the collection point. Aborting the job will also cancel any active trip.

Common Reasons
  • Car accident β€” on scene with police
  • Equipment malfunction β€” vehicle broken down
  • Blocked road β€” unable to proceed
  • Legal denial β€” customer denies access
  • Time expired β€” shift ended, cannot complete
  • Emergency β€” personal health issue
Request Body
JSON
{
  "reason": "Car accident β€” vehicle on side of road"
}
Response β€” 200 OK (No Active Trip)
JSON
{
  "job": { "id": "job-uuid-001", "status": "cancelled", "notes": "Car accident β€” vehicle on side of road" },
  "message": "job aborted"
}
Response β€” 200 OK (With Active Trip Cancelled)
JSON
{
  "job": { "id": "job-uuid-001", "status": "cancelled", "notes": "Car accident β€” vehicle on side of road" },
  "message": "job aborted",
  "trip_status": "cancelled",
  "note": "Active trip for this job was also cancelled"
}
Behavior

Automatically cancels any active trip (en_route, arrived, in_progress) for the job. Reason is stored in job notes and audit trail for investigation. Driver status reset to online.

GET /api/driver/stats Driver statistics β–Ύ
Response β€” 200 OK
JSON
{
  "stats": {
    "total": 142,
    "pending": 0,
    "assigned": 3,
    "in_progress": 1,
    "completed": 138,
    "completed_today": 5
  }
}

Driver: Job Photos πŸ“Έ

Pickup photos go to the trip endpoint
For the before and after photos of a pickup, use POST /api/driver/trips/{stop id}/photos (field photo): see A Route Job, Step by Step. The endpoint below counts photos per job, not per stop, and needs X-Company-ID (see Company context).

Photos are attached at the job level. When a driver visits a collection point, they take before/after photos of the work and upload them for the job. Drivers can upload up to 5 photos per phase (before/after) as proof-of-work. Photos are stored in Google Cloud Storage with full EXIF metadata (GPS, camera, timestamp) preserved for auditing. Uploads allowed while job is in-progress or within 48 hours after completion. Driver

POST /api/driver/jobs/{id}/photos Upload a job photo β–Ύ

Upload a photo for a job. The original file is stored as-is (no compression, no EXIF stripping). EXIF metadata is extracted and indexed for admin search.

πŸ“± Multipart upload
This endpoint uses multipart/form-data, not JSON. Send the image as a form file field.
Request β€” Multipart Form
FieldTypeRequiredDescription
filebinaryβœ…Image file (JPEG, PNG, WebP, HEIC). Max 50MB.
phasestring❌before or after (default: after)
latitudefloat❌Phone GPS latitude at upload time
longitudefloat❌Phone GPS longitude at upload time
cURL
curl -X POST \
  -H "Authorization: Bearer eyJhbG..." \
  -F "file=@photo.jpg" \
  -F "phase=after" \
  -F "latitude=-1.286" \
  -F "longitude=36.817" \
  https://getgomi.xyz/api/driver/jobs/{job_id}/photos
React Native
const formData = new FormData();
formData.append('file', {
  uri: photo.uri,          // from camera/gallery
  type: photo.type || 'image/jpeg',
  name: photo.fileName || 'photo.jpg',
});
formData.append('phase', 'after');
formData.append('latitude', String(location.latitude));
formData.append('longitude', String(location.longitude));

const res = await fetch(
  `https://getgomi.xyz/api/driver/jobs/${jobId}/photos`,
  {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${token}` },
    body: formData,
    // Do NOT set Content-Type β€” fetch sets it with boundary
  }
);
const data = await res.json();
// data.photo.public_url β€” display this
// data.remaining β€” photos left for this phase
Response β€” 201 Created
JSON
{
  "photo": {
    "id": "a1b2c3d4e5f6...",
    "job_id": "c88d57e3...",
    "driver_id": "d9f8e7c6...",
    "phase": "after",
    "gcs_path": "jobs/c88d57e3/after/a1b2c3d4.jpg",
    "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/c88d57e3/after/a1b2c3d4.jpg",
    "content_type": "image/jpeg",
    "size_bytes": 4521983,
    "latitude": -1.286,
    "longitude": 36.817,
    "exif_taken_at": "2026-07-07T10:30:00Z",
    "exif_lat": -1.2861,
    "exif_lng": 36.8172,
    "exif_make": "Samsung",
    "exif_model": "Galaxy S24",
    "exif_orientation": 1,
    "image_width": 4000,
    "image_height": 3000,
    "uploaded_at": "2026-07-07T10:31:15Z"
  },
  "remaining": 4
}
Error Responses
StatusMeaning
400Missing file, bad phase, unsupported image type
403Job not assigned to you
404Job not found
409Max 5 photos per phase reached, upload window closed (48h), or duplicate image (same MD5 hash)
413File too large (max 50MB)
503Photo uploads not configured (GCS not set up)
⚠️ EXIF Data Preserved
The original image is stored unmodified. EXIF GPS, timestamp, camera make/model are extracted and indexed in the database. Both phone GPS (from request) and EXIF GPS (from image) are stored separately for audit comparison.
GET /api/driver/jobs/{id}/photos List photos for a job β–Ύ

Returns all photos for a job, grouped by phase (before, then after).

Response β€” 200 OK
JSON
{
  "photos": [
    {
      "id": "a1b2c3d4...",
      "phase": "before",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/.../before/a1b2.jpg",
      "exif_taken_at": "2026-07-07T10:00:00Z",
      "exif_make": "Apple",
      "exif_model": "iPhone 16 Pro",
      "uploaded_at": "2026-07-07T10:01:00Z"
    },
    {
      "id": "e5f6g7h8...",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/.../after/e5f6.jpg",
      "uploaded_at": "2026-07-07T10:45:00Z"
    }
  ]
}

Driver: A Route Job, Step by Step 🧭

How the driver app runs a job on a route, from start to finish: start the trip, get the stops in the order the admin set, and at each stop take the photos and set the stop's status. Every call here works with the driver's JWT alone: no X-Company-ID header is needed, whichever company the job is in. Driver

1. Start the trip
POST /api/driver/trips/start
β†’ 2. Get the stops
GET /api/driver/trips?job_id=
β†’ 3. At each stop
photos, then status
β†’ 4. Complete the trip
POST /api/driver/trips/{trip id}/complete
β†’ 5. Complete the job
POST /api/driver/jobs/{job id}/complete
Two kinds of id: keep them apart
idWhere it comes fromWhat it is used for
trip idtrip.id in the answer of step 1GPS pings, arrive, and completing or cancelling the trip (step 4). 1 trip covers the whole route job
stop ideach entry's id in GET /api/driver/trips?job_id= (step 2)Everything at a stop: its photos (/api/driver/trips/{stop id}/photos) and its status (/api/driver/jobs/{job id}/stops/{stop id})

For a route job, the entries of the trips array in step 2 are the job's stops, not trips, even though the field is called trips. Each has its own id, collection point and status.

1. Start the trip

JSON
// POST /api/driver/trips/start
{ "job_id": "job_01", "latitude": 35.6812, "longitude": 139.7671 }

// Response: 201 Created
{
  "trip": {
    "id": "trip_01",                  // the trip id: keep it for step 4
    "job_id": "job_01",
    "status": "en_route",
    "started_at": "2026-10-31T08:00:00Z",
    ...
  },
  "next_ping_ms": 3000
}

Keep trip.id. Starting the trip also puts the job in_progress. A driver has 1 live trip at a time: with another one still live, the answer is 409 "You already have an active trip" with that trip in active_trip; complete or cancel it first. Start the trip before anything else: photos need a live trip on the job.

2. Get the stops, in the admin's order

JSON
// GET /api/driver/trips?job_id=job_01
// Response: 200 OK, 1 entry per stop of the route
{
  "trips": [
    {
      "id": "stop_a",                 // the stop id: use it for photos and status
      "job_id": "job_01",
      "route_id": "route_01",
      "collection_point_id": "cp_01",
      "stop_order": 0,                // 0, 1, 2, ... exactly as the admin ordered the route
      "status": "en_route",           // en_route until the driver sets another
      "arrived_at": null,
      "completed_at": null,
      "estimated_service_min": 10,
      "point_name": "Collection Point A",
      "point_address": "1-2-3 Shibuya, Tokyo",
      "point_area": "Shibuya",
      "point_lat": 35.6580,
      "point_lng": 139.7016,
      "point_contact_name": "...",
      "point_contact_phone": "...",
      "point_waste_type_id": "wt_01",
      "waste_type_name": "Burnable",
      "waste_type_icon": "πŸ”₯",
      "updated_at": "2026-10-31T08:00:00Z"
    },
    { "id": "stop_b", "stop_order": 1, "status": "en_route", ... },
    { "id": "stop_c", "stop_order": 2, "status": "en_route", ... }
  ]
}

3. At each stop: photos, then status

StepCallNotes
a. ArrivedPOST /api/driver/jobs/{job id}/stops/{stop id}
{"status": "arrived"}
Sets arrived_at (the first arrival is kept)
b. Before photosPOST /api/driver/trips/{stop id}/photos
form: photo = the image, phase = before
Optional, up to 5 per stop
c. After photosPOST /api/driver/trips/{stop id}/photos
form: photo = the image, phase = after
Optional, up to 5 per stop. phase defaults to after
d. CompletedPOST /api/driver/jobs/{job id}/stops/{stop id}
{"status": "completed"}
Photos are optional: the stop completes with none. With no after photo it shows No photo to dispatch

A stop's status is one of en_route (not reached yet), arrived, in_progress, completed or cancelled (skipped). The status call answers with the stop: {"stop": {"id": "stop_a", "status": "completed", "arrived_at": "...", "completed_at": "...", ...}}.

React Native: upload a photo of a stop
const form = new FormData();
form.append('phase', 'after');                 // 'before' or 'after'
form.append('photo', { uri: image.uri, name: 'pickup.jpg', type: 'image/jpeg' });

const res = await fetch(`${BASE}/api/driver/trips/${stop.id}/photos`, {
  method: 'POST',
  // Only the token: do NOT set Content-Type, fetch sets multipart/form-data with its boundary
  headers: { Authorization: `Bearer ${token}` },
  body: form,
});
// 201 Created
// { "photo_id": "ph_01",
//   "photo": { "id": "ph_01", "job_id": "job_01", "phase": "after", "collection_point_id": "cp_01",
//              "public_url": "https://storage.googleapis.com/...", ... },
//   "remaining": 4 }                           // after photos this stop can still take
Photo upload checklist
  • The path takes the stop id. The trip id works too, with the stop id in a stop_id form field; both file the photo under that stop.
  • The file field is named photo. (The older POST /api/driver/jobs/{id}/photos takes file, counts photos per job rather than per stop, and needs X-Company-ID: do not use it for pickups.)
  • JPEG, PNG, WebP or HEIC, up to 50MB. EXIF (time, GPS, camera) is kept.
  • Upload while the trip is live: before step 4.

To show a stop with its photos:

CallAnswer
GET /api/driver/trips/{stop id}trip (the job's trip), stop, collection_point_name, collection_point_address, reference_photos (the admin's guidance photos of the point) and proof_photos (this stop's before and after photos on this job)
GET /api/driver/trips/{stop id}/photos{"photos": [...]}: this stop's before and after photos on this job, each with its phase

4. Next stop, then complete the trip

Repeat step 3 for each stop, in stop_order. A stop the driver skips is set cancelled. After the last stop:

JSON
// POST /api/driver/trips/trip_01/complete
{ "latitude": 35.6580, "longitude": 139.7016 }

This takes the trip id, not a stop id. Once the trip is completed, photo uploads on the job answer 409 "this trip has ended (completed)", so take every photo first.

5. Complete the job

JSON
// POST /api/driver/jobs/job_01/complete
{ "notes": "", "next_status": "online" }

// Response: 200 OK
{ "job": { "id": "job_01", "status": "completed", ... }, "message": "job completed", "status": "online" }

After this the job's stops can no longer change (409 "this job is completed"). The next job, even on the same route, starts again from step 1 with its own stops and photos.

A single-point job (no route)

The same steps without stops: start the trip, then upload to POST /api/driver/trips/{trip id}/photos (no stop_id), up to 5 before and 5 after. Photos are optional: POST /api/driver/trips/{trip id}/complete and POST /api/driver/jobs/{job id}/complete work with none, and a job completed with no after photo shows No photo to dispatch.

Errors and what to do

StatusError messageCauseFix
404trip not foundThe id in /api/driver/trips/{id}/... is neither a trip nor a stopUse trip.id from step 1 or a stop's id from step 2
404no trip of yours on this stop's job: start one firstA stop id, but the driver has no trip on its jobStep 1: POST /api/driver/trips/start with the job's id
404stop not found on this jobThe stop id is of another job, or the job is not the driver'sTake the stop ids from GET /api/driver/trips?job_id= of this job
404stop not found on this trip's jobA trip id in the path with a stop_id of another jobSend the stop id of this trip's job, or put the stop id in the path
400stop_id is required on a job with a route: ...A trip id in the path on a route job, without stop_idPut the stop id in the path instead of the trip id
400phase must be 'before' or 'after'Any other phase, such as proofSend before or after, or leave it out for after
400missing 'photo' fieldThe image was sent under another field name (such as file), or the body is not multipartName the field photo; do not set Content-Type yourself
403unauthorized / trip does not belong to youAnother driver's tripUse the trip started by this driver
409maximum 5 after photos reached for this pickupThe stop already has 5 photos of that phaseNothing to do: 5 is the limit per phase per stop
409this trip has ended (completed)Uploading after the trip was completed or cancelledUpload before step 4; for more photos, start a new trip on the job
409this job is completed / this job is cancelledThe job is closedNothing to change on it; the next job starts fresh
409this job has ended: ongoing for more than 3 daysThe job was started more than 3 days ago, so it was cancelled automaticallyAsk dispatch for a new job
409You already have an active tripStarting a trip with another one still liveComplete or cancel active_trip first

Driver: Trip Tracking ⭐

The trip tracking system captures high-frequency GPS telemetry from driver devices during active collections. Trips link to jobs and provide real-time visibility for dispatch. Driver

Trip Lifecycle

start β†’ en_route β†’ ping Γ— N β†’ arrive β†’ arrived β†’ complete
POST /api/driver/trips/start Start a new trip β–Ύ

Initiates a trip linked to a job. The driver's status changes to on_job.

Request Body
JSON
{
  "job_id": "job-uuid-001",
  "latitude": 35.6812,
  "longitude": 139.7671
}
Response β€” 201 Created
JSON
{
  "trip": {
    "id": "trip-uuid-001",
    "job_id": "job-uuid-001",
    "driver_id": "driver-uuid",
    "status": "en_route",
    "start_latitude": 35.6812,
    "start_longitude": 139.7671,
    "started_at": "2026-04-14T08:15:00Z"
  },
  "next_ping_ms": 3000
}
POST /api/driver/trips/{id}/ping Send GPS telemetry ping β–Ύ

Compact GPS telemetry payload. Send at the interval specified by next_ping_ms in the response. Short field names minimize bandwidth on mobile networks.

Request Body
JSON
{
  "lat": 35.6815,
  "lng": 139.7680,
  "spd": 13.9,
  "hdg": 225,
  "acc": 8.5,
  "alt": 35,
  "batt": 92,
  "ts": "2026-04-14T05:00:00Z",
  "seq": 42
}
Response β€” 200 OK
JSON
{
  "ok": true,
  "ping_count": 42,
  "stored": true,
  "next_ping_ms": 3000
}

Ping Field Reference

FieldTypeReqDescription
latfloatβœ…Latitude (-90 to 90)
lngfloatβœ…Longitude (-180 to 180)
spdfloatSpeed in meters per second
hdgfloatHeading 0–360Β° (0=North, clockwise)
accfloatGPS accuracy in meters (lower = better)
altfloatAltitude in meters above sea level
battfloatDevice battery level 0–100
tsstringISO 8601 timestamp from client clock
seqintMonotonic sequence number (for ordering)

Adaptive Ping Frequency

The server returns next_ping_ms but the client should also adapt based on speed:

SpeedInterval
> 60 km/h2 seconds
30–60 km/h3 seconds
10–30 km/h5 seconds
< 10 km/h10 seconds
< 2 km/h (stopped)15 seconds
POST /api/driver/trips/{id}/ping/batch Batch send pings β–Ύ

Send multiple queued pings at once. Useful when the device was offline or to reduce HTTP overhead. Accepts Content-Encoding: gzip for compressed payloads.

πŸ’‘ Compression
For large batches (50+ pings), gzip the request body and set Content-Encoding: gzip to reduce bandwidth by ~80%.
Request Body
JSON
{
  "pings": [
    { "lat": 35.6812, "lng": 139.7671, "spd": 0, "seq": 1, "ts": "2026-04-14T08:15:00Z" },
    { "lat": 35.6815, "lng": 139.7680, "spd": 8.2, "seq": 2, "ts": "2026-04-14T08:15:05Z" },
    { "lat": 35.6820, "lng": 139.7695, "spd": 13.1, "seq": 3, "ts": "2026-04-14T08:15:08Z" }
  ]
}
Response β€” 200 OK
JSON
{
  "ok": true,
  "ping_count": 45,
  "stored": 3,
  "skipped": 0,
  "next_ping_ms": 3000
}
POST /api/driver/trips/{id}/arrive Mark arrival at destination β–Ύ
Request Body
JSON
{
  "latitude": 35.6580,
  "longitude": 139.7016
}
Response β€” 200 OK
JSON
{
  "trip": {
    "id": "trip-uuid-001",
    "status": "arrived",
    "arrived_at": "2026-04-14T08:32:00Z"
  }
}
POST /api/driver/trips/{id}/complete Complete trip β–Ύ
Request Body
JSON
{
  "latitude": 35.6580,
  "longitude": 139.7016,
  "notes": "All collected, area clean"
}
Response β€” 200 OK
JSON
{
  "trip": {
    "id": "trip-uuid-001",
    "status": "completed",
    "completed_at": "2026-04-14T08:45:00Z",
    "distance_meters": 4250,
    "duration_seconds": 1800
  },
  "stats": {
    "ping_count": 312,
    "avg_speed": 8.5
  }
}
POST /api/driver/trips/{id}/cancel Cancel trip β–Ύ
Response β€” 200 OK
JSON
{
  "trip": {
    "id": "trip-uuid-001",
    "status": "cancelled",
    "cancelled_at": "2026-04-14T08:20:00Z"
  }
}
GET /api/driver/trips List driver's trips with optional filters β–Ύ
Query Parameters
ParamTypeDescription
statusstringFilter by status: en_route, arrived, in_progress, completed, cancelled
job_idstringFilter by job ID β€” get all trips for a specific job. For a job on a route, trips holds the job's stops instead, in stop order: 1 object per stop with its id, status (the trip statuses, en_route until the driver sets another), arrived_at, completed_at, collection_point_id, point_name, point_lat and point_lng. Each job starts from a fresh slate: its own copy of the route's stops, made the first time they are asked for. Set a stop's status with POST /api/driver/jobs/{id}/stops/{stopId}. See A Route Job, Step by Step
limitintegerResults per page (default 20, max 100)
offsetintegerPagination offset (default 0)
Examples:
  • GET /api/driver/trips β€” All trips
  • GET /api/driver/trips?status=completed β€” Completed trips only
  • GET /api/driver/trips?job_id=job_011 β€” Trips for specific job
  • GET /api/driver/trips?status=completed&job_id=job_011 β€” Combined filters
Response β€” 200 OK
JSON
{
  "trips": [
    {
      "id": "trip-uuid-001",
      "job_id": "job-uuid-001",
      "driver_id": "driver-uuid",
      "status": "completed",
      "started_at": "2026-04-14T08:15:00Z",
      "arrived_at": "2026-04-14T08:32:00Z",
      "completed_at": "2026-04-14T08:45:00Z",
      "start_lat": 35.6812,
      "start_lng": 139.7671,
      "end_lat": 35.6580,
      "end_lng": 139.7016,
      "distance_meters": 4250,
      "duration_seconds": 1800,
      "job_title": "Pickup at Tokyo Tower",
      "job_address": "4-2-8 Shiba-koen",
      "photos": [
        {
          "id": "ph_001",
          "phase": "before",
          "public_url": "https://storage.googleapis.com/...",
          "exif_taken_at": "2026-04-14T08:10:00Z",
          "latitude": 35.6586,
          "longitude": 139.7454,
          "exif_make": "Apple",
          "exif_model": "iPhone 15 Pro"
        },
        {
          "id": "ph_002",
          "phase": "after",
          "public_url": "https://storage.googleapis.com/...",
          "exif_taken_at": "2026-04-14T08:40:00Z"
        }
      ]
    }
  ]
}
Note

Responses include job title & address and before/after photos with EXIF metadata (camera, location, timestamp).

GET /api/driver/trips/{id} Get trip detail with enrichment β–Ύ
Path Parameters
ParamTypeDescription
idstringTrip ID, or the id of a stop of a route job from GET /api/driver/trips?job_id=: the answer is then about that stop, on the caller's latest trip on its job
Response β€” 200 OK
JSON
{
  "trip": {
    "id": "trip-uuid-001",
    "job_id": "job-uuid-001",
    "driver_id": "driver-uuid",
    "status": "completed",
    "start_lat": 35.6812,
    "start_lng": 139.7671,
    "end_lat": 35.6580,
    "end_lng": 139.7016,
    "distance_meters": 4250,
    "duration_seconds": 1800,
    "started_at": "2026-04-14T08:15:00Z",
    "arrived_at": "2026-04-14T08:32:00Z",
    "completed_at": "2026-04-14T08:45:00Z"
  },
  "job_title": "Pickup at Tokyo Tower",
  "job_address": "4-2-8 Shiba-koen",
  "photos": [
    {
      "id": "ph_001",
      "phase": "before",
      "public_url": "https://storage.googleapis.com/...",
      "exif_taken_at": "2026-04-14T08:10:00Z",
      "latitude": 35.6586,
      "longitude": 139.7454,
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro"
    },
    {
      "id": "ph_002",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/...",
      "exif_taken_at": "2026-04-14T08:40:00Z",
      "latitude": 35.6586,
      "longitude": 139.7454,
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro"
    }
  ],
  "stats": {
    "ping_count": 312,
    "avg_speed": 8.5
  }
}
Note

Includes job details (title, address) and before/after photos with location metadata.

GET /api/driver/trips/{id}/pings Get trip pings β–Ύ

Returns all stored GPS pings for a trip, ordered by sequence number.

Response β€” 200 OK
JSON
{
  "pings": [
    { "lat": 35.6812, "lng": 139.7671, "spd": 0, "hdg": 0, "acc": 5.2, "seq": 1, "ts": "2026-04-14T08:15:00Z" },
    { "lat": 35.6815, "lng": 139.7680, "spd": 8.2, "hdg": 45, "acc": 6.1, "seq": 2, "ts": "2026-04-14T08:15:05Z" }
  ],
  "trip": {
    "id": "trip-uuid-001",
    "status": "completed"
  }
}

React Native TripTracker

Complete implementation using expo-location with adaptive frequency, offline queuing, and batch uploads:

React Native / TypeScript
import * as Location from 'expo-location';

const BASE = 'https://getgomi.xyz';

interface Ping {
  lat: number; lng: number; spd: number; hdg: number;
  acc: number; alt: number; batt: number; ts: string; seq: number;
}

class TripTracker {
  private tripId: string | null = null;
  private apiKey: string;
  private seq = 0;
  private queue: Ping[] = [];
  private intervalId: ReturnType<typeof setTimeout> | null = null;
  private locationSub: Location.LocationSubscription | null = null;
  private nextPingMs = 3000;
  private lastPing: Ping | null = null;
  private sending = false;

  constructor(apiKey: string) {
    this.apiKey = apiKey;
  }

  private async request(path: string, body?: object) {
    const res = await fetch(BASE + path, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
      },
      body: body ? JSON.stringify(body) : undefined,
    });
    if (!res.ok) {
      const e = await res.json().catch(() => ({}));
      throw new Error(e.error || res.statusText);
    }
    return res.json();
  }

  private getIntervalMs(speedMs: number): number {
    const kmh = speedMs * 3.6;
    if (kmh > 60) return 2000;
    if (kmh > 30) return 3000;
    if (kmh > 10) return 5000;
    if (kmh > 2) return 10000;
    return 15000;
  }

  async start(jobId: string): Promise<void> {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') throw new Error('Location permission denied');

    const loc = await Location.getCurrentPositionAsync({
      accuracy: Location.Accuracy.High,
    });

    const data = await this.request('/api/driver/trips/start', {
      job_id: jobId,
      latitude: loc.coords.latitude,
      longitude: loc.coords.longitude,
    });

    this.tripId = data.trip.id;
    this.nextPingMs = data.next_ping_ms || 3000;
    this.seq = 0;
    this.queue = [];

    // Start watching location
    this.locationSub = await Location.watchPositionAsync(
      {
        accuracy: Location.Accuracy.High,
        distanceInterval: 5,
        timeInterval: 1000,
      },
      (location) => {
        this.lastPing = {
          lat: location.coords.latitude,
          lng: location.coords.longitude,
          spd: location.coords.speed || 0,
          hdg: location.coords.heading || 0,
          acc: location.coords.accuracy || 0,
          alt: location.coords.altitude || 0,
          batt: 0, // integrate battery API separately
          ts: new Date(location.timestamp).toISOString(),
          seq: ++this.seq,
        };
      },
    );

    // Start ping loop
    this.schedulePing();
  }

  private schedulePing() {
    if (this.intervalId) clearTimeout(this.intervalId);
    this.intervalId = setTimeout(async () => {
      await this.sendPing();
      this.schedulePing();
    }, this.nextPingMs);
  }

  private async sendPing(): Promise<void> {
    if (!this.tripId || !this.lastPing || this.sending) return;
    this.sending = true;

    const ping = { ...this.lastPing };
    this.queue.push(ping);

    // Adaptive interval based on speed
    this.nextPingMs = this.getIntervalMs(ping.spd);

    try {
      if (this.queue.length > 1) {
        // Batch send queued pings
        const data = await this.request(
          `/api/driver/trips/${this.tripId}/ping/batch`,
          { pings: this.queue },
        );
        this.nextPingMs = data.next_ping_ms || this.nextPingMs;
        this.queue = []; // Clear queue on success
      } else {
        // Single ping
        const data = await this.request(
          `/api/driver/trips/${this.tripId}/ping`,
          ping,
        );
        this.nextPingMs = data.next_ping_ms || this.nextPingMs;
        this.queue = [];
      }
    } catch (err) {
      // Keep pings in queue for next batch attempt
      console.warn('Ping failed, queued:', this.queue.length);
    } finally {
      this.sending = false;
    }
  }

  async arrive(): Promise<any> {
    if (!this.tripId || !this.lastPing) throw new Error('No active trip');
    return this.request(`/api/driver/trips/${this.tripId}/arrive`, {
      latitude: this.lastPing.lat,
      longitude: this.lastPing.lng,
    });
  }

  async complete(notes?: string): Promise<any> {
    if (!this.tripId || !this.lastPing) throw new Error('No active trip');

    // Flush remaining pings
    if (this.queue.length > 0) {
      await this.sendPing();
    }

    const result = await this.request(
      `/api/driver/trips/${this.tripId}/complete`,
      {
        latitude: this.lastPing.lat,
        longitude: this.lastPing.lng,
        notes: notes || '',
      },
    );

    this.cleanup();
    return result;
  }

  async cancel(): Promise<any> {
    if (!this.tripId) throw new Error('No active trip');
    const result = await this.request(
      `/api/driver/trips/${this.tripId}/cancel`,
    );
    this.cleanup();
    return result;
  }

  private cleanup() {
    if (this.intervalId) clearTimeout(this.intervalId);
    if (this.locationSub) this.locationSub.remove();
    this.tripId = null;
    this.lastPing = null;
    this.queue = [];
    this.seq = 0;
  }

  get isActive(): boolean {
    return this.tripId !== null;
  }

  get currentTripId(): string | null {
    return this.tripId;
  }
}

export default TripTracker;

// --- Usage ---
// const tracker = new TripTracker('gomi_xxx...');
// await tracker.start('job-uuid-001');
// ... driving ...
// await tracker.arrive();
// ... collecting waste ...
// const result = await tracker.complete('All done');
// console.log(result.trip.distance_meters);

SSE Real-Time (Dispatch)

Server-Sent Events stream for live trip updates on the dispatch dashboard. Dispatch

GET /api/dispatch/trips/live EventSource SSE stream β–Ύ

Opens a persistent SSE connection for the live positions of the company's drivers. A browser signed in to the console sends its session cookie. Elsewhere, send a JWT: as a query parameter, since EventSource doesn't support custom headers, or as Authorization: Bearer where headers can be set. An API key is refused (403). Each event's data is { "type": "<event>", "data": {...} }; a : keepalive comment comes every 15 seconds.

Query Parameters
ParamTypeDescription
keystringA JWT (from POST /auth/token), when there is no session

Event Types

init
Connection established. data: the live trips, an array as GET /api/dispatch/trips/active answers.
trip_start
A driver started a new trip. data: { "trip", "driver_id", "driver_name", "job_title", "job_address", "job_lat", "job_lng", "route_id" }
ping
GPS telemetry update. data: { "trip_id", "driver_id", "lat", "lng", "spd" (m/s), "hdg", "batt", "ts", "stored" }; a batch sends "batch": true, "batch_size" instead of hdg, batt and stored
trip_arrive
Driver arrived at destination. data: { "trip", "driver_id" }
trip_complete
Trip completed. data: { "trip", "driver_id" }
trip_cancel
Trip cancelled, or ended by the server (a job ongoing for more than 3 days; a driver removed or disabled). data: { "trip", "driver_id" }

React Native EventSource Example

React Native / TypeScript
import { useEffect, useRef, useCallback, useState } from 'react';

interface TripPing {
  trip_id: string;
  lat: number;
  lng: number;
  spd: number;
  hdg: number;
  ts: string;
}

interface Trip {
  id: string;
  driver_id: string;
  job_id: string;
  status: string;
  start_latitude: number;
  start_longitude: number;
}

const BASE = 'https://getgomi.xyz';

// jwt: from POST /auth/token (an API key is refused here)
export function useDispatchSSE(jwt: string) {
  const esRef = useRef<EventSource | null>(null);
  const [trips, setTrips] = useState<Map<string, Trip>>(new Map());
  const [latestPing, setLatestPing] = useState<TripPing | null>(null);

  const connect = useCallback(() => {
    if (esRef.current) esRef.current.close();

    const es = new EventSource(
      `${BASE}/api/dispatch/trips/live?key=${encodeURIComponent(jwt)}`
    );
    esRef.current = es;

    es.addEventListener('init', (e: MessageEvent) => {
      const { data } = JSON.parse(e.data); // the live trips
      const map = new Map<string, Trip>();
      data.forEach((t: Trip) => map.set(t.id, t));
      setTrips(map);
    });

    es.addEventListener('trip_start', (e: MessageEvent) => {
      const { trip } = JSON.parse(e.data).data;
      setTrips(prev => new Map(prev).set(trip.id, trip));
    });

    es.addEventListener('ping', (e: MessageEvent) => {
      const ping: TripPing = JSON.parse(e.data).data;
      setLatestPing(ping);
    });

    es.addEventListener('trip_arrive', (e: MessageEvent) => {
      const { trip } = JSON.parse(e.data).data;
      setTrips(prev => {
        const next = new Map(prev);
        next.set(trip.id, { ...next.get(trip.id)!, ...trip });
        return next;
      });
    });

    es.addEventListener('trip_complete', (e: MessageEvent) => {
      const { trip } = JSON.parse(e.data).data;
      setTrips(prev => {
        const next = new Map(prev);
        next.delete(trip.id);
        return next;
      });
    });

    es.addEventListener('trip_cancel', (e: MessageEvent) => {
      const { trip } = JSON.parse(e.data).data;
      setTrips(prev => {
        const next = new Map(prev);
        next.delete(trip.id);
        return next;
      });
    });

    es.onerror = () => {
      es.close();
      // Reconnect after 3 seconds
      setTimeout(connect, 3000);
    };
  }, [jwt]);

  useEffect(() => {
    connect();
    return () => esRef.current?.close();
  }, [connect]);

  return { trips, latestPing };
}

// --- Usage in a component ---
// const { trips, latestPing } = useDispatchSSE(jwt); // a JWT, renewed with POST /auth/refresh
// trips is a Map<tripId, Trip> of all active trips
// latestPing updates on every GPS telemetry event
GET /api/driver/trips/{id} Get trip details with reference + proof photos β–Ύ
Path Parameters
ParamTypeDescription
idstringTrip ID, or the id of a stop of a route job from GET /api/driver/trips?job_id=: the answer is then about that stop, on the caller's latest trip on its job
Example:
  • GET /api/driver/trips/trip_uuid_123
Response β€” 200 OK
JSON
{
  "trip": {
    "id": "trip_uuid_123",
    "job_id": "job_uuid_456",
    "driver_id": "driver_uuid_789",
    "status": "completed",
    "started_at": "2026-10-13T08:00:00Z",
    "arrived_at": "2026-10-13T08:15:00Z",
    "completed_at": "2026-10-13T08:45:00Z",
    "start_lat": 35.6812,
    "start_lng": 139.7671,
    "end_lat": 35.6580,
    "end_lng": 139.7016,
    "distance_meters": 4250,
    "duration_seconds": 1800
  },
  "job_title": "Pickup at Collection Point A",
  "job_address": "123 Main St, Tokyo",
  "collection_point_name": "Collection Point A",
  "collection_point_address": "123 Main St, Tokyo",
  "reference_photos": [
    {
      "id": "ref_photo_001",
      "collection_point_id": "cp_001",
      "public_url": "https://storage.googleapis.com/...",
      "caption": "Front entrance where to drop bins",
      "sort_order": 0,
      "created_at": "2026-10-10T14:30:00Z"
    }
  ],
  "proof_photos": [
    {
      "id": "proof_photo_001",
      "photo_type": "driver",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/...",
      "uploaded_at": "2026-10-13T08:42:00Z",
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro",
      "latitude": 35.6586,
      "longitude": 139.7454
    }
  ]
}
Note

reference_photos are admin-uploaded guidance (same for all drivers visiting this collection point). proof_photos are the driver's before and after photos: of the job, or of the stop when id is a stop's. With a stop's id the answer also has stop, the stop with its status.

POST /api/driver/trips/{id}/photos Upload a before or after photo of a pickup during a trip β–Ύ
Path Parameters
ParamTypeDescription
idstringTrip ID, or the id of a stop of a route job as listed by GET /api/driver/trips?job_id=: the photo is then of that stop, on the caller's latest trip on its job (404 when there is none yet). The same goes for GET /api/driver/trips/{id} and GET /api/driver/trips/{id}/photos
Request Body β€” multipart/form-data
FieldTypeRequiredDescription
photofileβœ“Image file (JPEG, PNG, WebP, HEIC). Max 50MB.
phasestringbefore or after the pickup; after when left out
stop_idstringon a route job, with a trip IDThe stop the photo is of: its id in GET /api/driver/trips?job_id=. Not needed when the path has the stop's id
Constraints:
  • Up to 5 before and 5 after photos per pickup: a stop of a route job, or a single-point job. Another job, even on the same route, starts again
  • Photos are optional: a pickup (a stop, or a single-point job) completes with none. A pickup completed with no after photo shows No photo to dispatch (GET /api/dispatch/jobs and GET /api/dispatch/jobs/{id})
  • Supported formats: JPEG, PNG, WebP, HEIC
  • File size: up to 50MB
  • EXIF metadata automatically extracted
Response β€” 201 Created
JSON
{
  "photo_id": "proof_photo_001",
  "photo": {
    "id": "proof_photo_001",
    "job_id": "job_uuid_456",
    "driver_id": "driver_uuid_789",
    "phase": "after",
    "public_url": "https://storage.googleapis.com/...",
    "content_type": "image/jpeg",
    "size_bytes": 1024576,
    "latitude": 35.6586,
    "longitude": 139.7454,
    "exif_taken_at": "2026-10-13T08:42:15Z",
    "exif_make": "Apple",
    "exif_model": "iPhone 15 Pro",
    "image_width": 3024,
    "image_height": 4032,
    "uploaded_at": "2026-10-13T08:42:30Z",
    "photo_type": "driver"
  },
  "remaining": 4
}
Note

A photo is filed under the pickup's collection point: the stop's on a route job, else the job's. Only the driver of the trip can upload, while the trip is live. remaining is how many more photos of that phase the pickup takes (max 5).

GET /api/driver/trips/{id}/photos List proof photos for this trip β–Ύ
Path Parameters
ParamTypeDescription
idstringTrip ID, or the id of a stop of a route job from GET /api/driver/trips?job_id=: the answer is then about that stop, on the caller's latest trip on its job
Example:
  • GET /api/driver/trips/trip_uuid_123/photos
Response β€” 200 OK
JSON
{
  "photos": [
    {
      "id": "proof_photo_001",
      "job_id": "job_uuid_456",
      "driver_id": "driver_uuid_789",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/...",
      "content_type": "image/jpeg",
      "size_bytes": 1024576,
      "latitude": 35.6586,
      "longitude": 139.7454,
      "exif_taken_at": "2026-10-13T08:42:15Z",
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro",
      "image_width": 3024,
      "image_height": 4032,
      "uploaded_at": "2026-10-13T08:42:30Z",
      "photo_type": "driver"
    },
    {
      "id": "proof_photo_002",
      "job_id": "job_uuid_456",
      "driver_id": "driver_uuid_789",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/...",
      "content_type": "image/jpeg",
      "size_bytes": 1156432,
      "latitude": 35.6580,
      "longitude": 139.7016,
      "exif_taken_at": "2026-10-13T08:43:20Z",
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro",
      "uploaded_at": "2026-10-13T08:43:45Z",
      "photo_type": "driver"
    }
  ]
}
Note

Returns the driver's before and after photos of the trip's job; with a stop's id, those of that stop on its job. Reference photos are NOT included here (see GET /api/driver/trips/{id} for both).

Dispatch: Jobs

Create, manage, and assign collection jobs to drivers. Dispatch

POST /api/dispatch/jobs Create job β–Ύ
Request Body
JSON
{
  "title": "Meguro Ward - Recyclables",
  "address": "4-5-6 Meguro, Meguro-ku, Tokyo",
  "latitude": 35.6339,
  "longitude": 139.7154,
  "waste_type_id": "wt-uuid-002",
  "priority": "high",
  "scheduled_date": "2026-04-15",
  "estimated_volume": 5.0,
  "notes": "Large apartment complex, use rear entrance"
}
Response β€” 201 Created
JSON
{
  "job": {
    "id": "job-uuid-002",
    "title": "Meguro Ward - Recyclables",
    "status": "pending",
    "created_at": "2026-04-14T10:00:00Z"
  }
}
GET /api/dispatch/jobs List all jobs β–Ύ
Query Parameters
ParamTypeDescription
statusstringFilter by status
driver_idstringFilter by assigned driver
datestringFilter by scheduled date (YYYY-MM-DD)
limitintMax results (default 50)
offsetintPagination offset
Response β€” 200 OK
JSON
{
  "jobs": [ { "id": "...", "title": "...", "status": "completed", "no_photo_count": 1, ... } ],
  "total": 47
}

no_photo_count: how many of the job's pickups were completed with no after photo, which drivers may skip; the console shows them No photo. A pickup is a stop of the job when it has stops, else the job itself. It is worked out from the photos, so an after photo uploaded later clears it.

GET /api/dispatch/jobs/{id} Get job detail β–Ύ

Returns full job details including assigned driver information, the job's events, its stops in the admin's order (empty for a job with none) and no_photo_count, as in the jobs list.

JSON
{
  "job": { "id": "job_01", "status": "in_progress", "route_id": "route_01", ... },
  "events": [ ... ],
  "stops": [
    { "id": "stop_a", "collection_point_id": "cp_01", "stop_order": 0, "status": "completed",
      "arrived_at": "...", "completed_at": "...", "departed_at": "...", "point_name": "Collection Point A",
      "before_photos": 1, "after_photos": 0, "no_photo": true,
      "reference_photos": [ { "id": "sp_01", "public_url": "https://storage.googleapis.com/...", "caption": "Bin station" } ],
      "photos": [ { "id": "ph_01", "public_url": "https://storage.googleapis.com/...", "phase": "before", "uploaded_at": "..." } ] },
    { "id": "stop_b", "stop_order": 1, "status": "completed", "before_photos": 2, "after_photos": 3, "no_photo": false, ... },
    { "id": "stop_c", "stop_order": 2, "status": "en_route", "before_photos": 0, "after_photos": 0, "no_photo": false, ... }
  ],
  "no_photo_count": 1
}

arrived_at is the driver's first arrival at the stop, and departed_at is when a completed stop was completed: completing a stop is departing it (a skipped, cancelled stop has none). no_photo marks a stop completed with no after photo: drivers may skip photos, and the console shows it No photo. reference_photos are the admin's photos of the stop's point, and photos the driver's at the stop on this job, oldest first. A stop since taken off the route is listed last.

PUT /api/dispatch/jobs/{id} Update job β–Ύ

Update any mutable job fields (title, address, coordinates, notes, priority, scheduled_date, estimated_volume).

POST /api/dispatch/jobs/{id}/assign Assign driver β–Ύ
Request Body
JSON
{
  "driver_id": "driver-uuid"
}
Response β€” 200 OK
JSON
{
  "job": { "id": "job-uuid-002", "status": "assigned", "driver_id": "driver-uuid" },
  "message": "job assigned"
}
POST /api/dispatch/jobs/{id}/cancel Cancel job β–Ύ
Request Body
JSON
{
  "notes": "Customer cancelled pickup"
}
POST /api/dispatch/jobs/{id}/reassign Reassign job to different driver β–Ύ

Reassign an existing job to a different driver. The job must not be completed or cancelled.

Request Body
JSON
{
  "driver_id": "new-driver-uuid"
}
Response β€” 200 OK
JSON
{
  "job": {
    "id": "job-uuid-002",
    "status": "assigned",
    "driver_id": "new-driver-uuid"
  },
  "message": "job reassigned"
}
POST /api/dispatch/jobs/auto-assign Auto-assign pending jobs β–Ύ

Plans which online driver (with a known location) takes which pending job with no driver, nearest first, and assigns the plan only with "commit": true. Optional body: { "driver_ids": [...], "job_ids": [...], "commit": false }.

Response β€” 200 OK
JSON
{
  "assignments": [
    { "driver_id": "usr_d001", "driver_name": "Kenji Yamada", "start_lat": 35.68, "start_lng": 139.76,
      "jobs": [{ "job_id": "job_001", "title": "...", "distance_km": 5.2, "order": 1, ... }],
      "total_km": 5.2 }
  ],
  "total_jobs": 2,
  "total_drivers": 1,
  "assigned_count": 0,
  "dry_run": true,
  "message": "Preview only. Set commit=true to apply assignments."
}
GET /api/dispatch/jobs/{id}/events Job event audit log β–Ύ

Returns the full event history for a job, oldest first: creation, assignment, status changes, reassignment, completion, and the driver's way through it (the same list is events in GET /api/dispatch/jobs/{id}).

Response β€” 200 OK
JSON
{
  "events": [
    { "id": "evt_01", "job_id": "job_01", "event_type": "assigned", "actor_id": "usr_admin",
      "old_value": "", "new_value": "usr_driver", "details": "", "created_at": "2026-11-04T08:00:00Z",
      "actor_first_name": "...", "actor_last_name": "..." },
    { "id": "evt_02", "event_type": "trip_started", "new_value": "trip_01", "created_at": "2026-11-04T08:10:00Z", ... },
    { "id": "evt_03", "event_type": "arrived", "old_value": "en_route", "new_value": "arrived",
      "details": "Collection Point A", "created_at": "2026-11-04T08:25:00Z", ... },
    { "id": "evt_04", "event_type": "photo_uploaded", "new_value": "ph_01",
      "details": "after photo, Collection Point A", "created_at": "2026-11-04T08:31:00Z", ... },
    { "id": "evt_05", "event_type": "departed", "old_value": "arrived", "new_value": "completed",
      "details": "Collection Point A", "created_at": "2026-11-04T08:33:00Z", ... }
  ]
}

The driver's events:

event_typeWhenold_value / new_valuedetails
trip_startedThe driver starts a trip on the job/ the trip id
arrivedThe driver sets a stop arrivedthe stop's status before / arrivedthe point's name
in_progressA stop set in_progressbefore / in_progressthe point's name
departedA stop set completed: completing a stop is departing itbefore / completedthe point's name
skippedA stop set cancelledbefore / cancelledthe point's name
en_routeA stop set back to en_routebefore / en_routethe point's name
photo_uploadedA photo through POST /api/driver/trips/{id}/photos (the older POST /api/driver/jobs/{id}/photos logs one too, with the phase as new_value)/ the photo idbefore photo, <point> or after photo, <point>
trip_completed, trip_cancelledThe trip endsthe trip's status before / after

A stop status sent again (the same as the stop has) is not a new event. These are logged from November 2026 on; for earlier stops, arrived_at and departed_at on the stops of GET /api/dispatch/jobs/{id} have the times.

Dispatch: Active Trips

GET /api/dispatch/trips/active List active trips β–Ύ

Returns all currently active trips with embedded driver and job info for the dispatch map.

Response β€” 200 OK
JSON
{
  "trips": [
    {
      "id": "trip-uuid-001",
      "status": "en_route",
      "started_at": "2026-04-14T08:15:00Z",
      "latest_lat": 35.6820,
      "latest_lng": 139.7695,
      "latest_spd": 13.1,
      "driver": {
        "id": "driver-uuid",
        "first_name": "Tanaka",
        "last_name": "Yuki",
        "avatar_url": "..."
      },
      "job": {
        "id": "job-uuid-001",
        "title": "Shibuya Ward - Burnable",
        "address": "1-2-3 Shibuya, Shibuya-ku, Tokyo"
      }
    }
  ]
}
GET /api/dispatch/trips/{id}/pings Get trip pings (dispatch) β–Ύ

Same as the driver endpoint but accessible to dispatch users. Returns all pings for route visualization.

Response β€” 200 OK
JSON
{
  "pings": [
    { "lat": 35.6812, "lng": 139.7671, "spd": 0, "seq": 1, "ts": "..." },
    { "lat": 35.6815, "lng": 139.7680, "spd": 8.2, "seq": 2, "ts": "..." }
  ],
  "trip": { "id": "trip-uuid-001", "status": "en_route" }
}

Dispatch: Collection Points

Manage pickup locations that can be added as stops on routes. Dispatch

GET /api/dispatch/collection-points List collection points β–Ύ

Returns a paginated list of collection points. Use search to filter by name or address.

Query Parameters
ParamTypeDescription
searchstringFilter by name or address
pageintPage number (default 1)
limitintResults per page (default 20)
Response β€” 200 OK
JSON
{
  "collection_points": [
    {
      "id": "cp-uuid-001",
      "name": "Shibuya Station Drop-off",
      "address": "2-24-12 Shibuya, Shibuya-ku, Tokyo",
      "area_name": "Shibuya",
      "latitude": 35.6580,
      "longitude": 139.7016,
      "country_code": "JP",
      "contact_name": "Sato Kenji",
      "contact_phone": "+81-3-1234-5678",
      "waste_type_id": "wt-uuid-001",
      "notes": "Rear loading bay",
      "created_at": "2026-03-01T09:00:00Z"
    }
  ],
  "total": 34
}
GET /api/dispatch/collection-points/{id} Get collection point β–Ύ

Returns a single collection point by ID.

Response β€” 200 OK
JSON
{
  "collection_point": {
    "id": "cp-uuid-001",
    "name": "Shibuya Station Drop-off",
    "address": "2-24-12 Shibuya, Shibuya-ku, Tokyo",
    "area_name": "Shibuya",
    "latitude": 35.6580,
    "longitude": 139.7016,
    "country_code": "JP",
    "contact_name": "Sato Kenji",
    "contact_phone": "+81-3-1234-5678",
    "waste_type_id": "wt-uuid-001",
    "notes": "Rear loading bay",
    "created_at": "2026-03-01T09:00:00Z"
  }
}
POST /api/dispatch/collection-points Create collection point β–Ύ

Create a new collection point (pickup location). Its country_code is where the latitude and longitude are, found by address lookup; a country_code sent is ignored. A point outside Japan and Uganda is refused with 400.

Request Body
JSON
{
  "name": "Meguro Apartment Complex",
  "address": "4-5-6 Meguro, Meguro-ku, Tokyo",
  "area_name": "Meguro",
  "latitude": 35.6339,
  "longitude": 139.7154,
  "contact_name": "Yamamoto Aiko",
  "contact_phone": "+81-3-9876-5432",
  "waste_type_id": "wt-uuid-002",
  "notes": "Use rear entrance, buzzer #203"
}
Response β€” 201 Created
JSON
{
  "collection_point": {
    "id": "cp-uuid-002",
    "name": "Meguro Apartment Complex",
    "address": "4-5-6 Meguro, Meguro-ku, Tokyo",
    "area_name": "Meguro",
    "latitude": 35.6339,
    "longitude": 139.7154,
    "country_code": "JP",
    "contact_name": "Yamamoto Aiko",
    "contact_phone": "+81-3-9876-5432",
    "waste_type_id": "wt-uuid-002",
    "notes": "Use rear entrance, buzzer #203",
    "created_at": "2026-04-14T12:00:00Z"
  }
}
PUT /api/dispatch/collection-points/{id} Update collection point β–Ύ

Update an existing collection point. Accepts the same fields as create; latitude and longitude are required, and the country is found again from them.

Request Body
JSON
{
  "name": "Meguro Apartment Complex (Updated)",
  "latitude": 35.6339,
  "longitude": 139.7154,
  "contact_phone": "+81-3-1111-2222",
  "notes": "New gate code: 4521"
}
Response β€” 200 OK
JSON
{
  "collection_point": {
    "id": "cp-uuid-002",
    "name": "Meguro Apartment Complex (Updated)",
    "notes": "New gate code: 4521",
    "...": "..."
  }
}
DELETE /api/dispatch/collection-points/{id} Delete collection point β–Ύ

Permanently delete a collection point. Fails if the point is currently used as a stop on an active route.

Response β€” 200 OK
JSON
{
  "message": "collection point deleted"
}

Site Photos (Collection Point Reference Images)

Upload reference photos for collection points to help drivers locate pickup sites. Max 20 photos per point. Photos are publicly accessible. Duplicate uploads are rejected by MD5 hash. Dispatch

POST /api/dispatch/collection-points/{id}/photos Upload site photo β–Ύ

Upload a reference photo for a collection point. Multipart form upload.

FieldTypeDescription
filefile (required)Image file (JPEG, PNG, WebP, HEIC). Max 50MB.
captionstringOptional caption describing the photo
cURL
curl -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-Company-ID: $COMPANY_ID" \
  -F "file=@entrance.jpg" \
  -F "caption=Blue gate on left side" \
  https://getgomi.xyz/api/dispatch/collection-points/{id}/photos
Response β€” 201 Created
JSON
{
  "photo": {
    "id": "9056a894eb3b2439...",
    "collection_point_id": "42f9ce45...",
    "public_url": "https://storage.googleapis.com/gomi_storage_public/sites/.../photo.jpg",
    "caption": "Blue gate on left side",
    "content_type": "image/jpeg",
    "size_bytes": 245000,
    "md5_hash": "5200db9b77199d5a...",
    "sort_order": 0,
    "created_at": "2026-09-15T11:08:08Z",
    "company_id": "abc..."
  }
}
Error β€” 409 Conflict (duplicate)
JSON
{"error": "duplicate photo \u2014 this image has already been uploaded"}
StatusMeaning
201Photo uploaded successfully
409Duplicate image (same MD5) or max 20 photos reached
413File too large (max 50MB)
GET /api/dispatch/collection-points/{id}/photos List site photos β–Ύ

Returns all reference photos for a collection point, ordered by sort_order.

Response β€” 200 OK
JSON
{
  "photos": [
    {
      "id": "9056a894...",
      "collection_point_id": "42f9ce45...",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/sites/.../photo.jpg",
      "caption": "Blue gate on left side",
      "content_type": "image/jpeg",
      "size_bytes": 245000,
      "md5_hash": "5200db9b...",
      "sort_order": 0,
      "created_at": "2026-09-15T11:08:08Z"
    }
  ]
}
PATCH /api/dispatch/collection-points/{id}/photos/{photoId} Update photo caption β–Ύ

Update the caption of a site photo.

JSON
{"caption": "Look for the blue gate on the left"}
DELETE /api/dispatch/collection-points/{id}/photos/{photoId} Delete single photo β–Ύ

Delete a single site photo. Returns 204 No Content.

POST /api/dispatch/collection-points/{id}/photos/batch-delete Batch delete photos β–Ύ

Delete multiple site photos at once. All photo IDs must belong to the specified collection point.

JSON Request
{"ids": ["photo_id_1", "photo_id_2", "photo_id_3"]}
Response β€” 200 OK
JSON
{"deleted": 3}

Driver Access to Site Photos

Drivers can view site photos (read-only) to help locate collection points:

GET /api/driver/collection-points/{id}/photos View site reference photos (driver) β–Ύ

Returns the same photos as the dispatch endpoint. Read-only for drivers.

Answers for a collection point in any company the driver belongs to: no X-Company-ID is needed (see Company context). A point of a company the driver is not in answers 404 "collection point not found". The same goes for GET /api/driver/collection-points/{id}/photo-gallery, GET /api/driver/collection-points/{id}/job-photos and GET /api/driver/jobs/{id}/collection-point-photos, which answer 403 "collection point not in your company" instead. On a route job, GET /api/driver/trips/{stop id} has the same photos in reference_photos.

Also included automatically in GET /api/driver/jobs/{id} β€” when a job is linked to a collection point with photos, the response includes a site_photos array alongside the job data:

JSON
{
  "job": {"id": "...", "title": "Pickup at Shibuya", "collection_point_id": "cp_abc", ...},
  "site_photos": [
    {"id": "...", "public_url": "https://...", "caption": "Blue gate entrance"}
  ]
}

The site_photos field is omitted when no collection point is linked or no photos exist.

Dispatch: Routes

Create and manage collection routes with ordered stops. Routes can be scheduled and assigned to drivers. Dispatch

POST /api/dispatch/routes Create route β–Ύ

Create a new collection route.

Request Body
JSON
{
  "name": "Shibuya Morning Route",
  "area_name": "Shibuya",
  "country_code": "JP",
  "schedule_days": ["monday", "wednesday", "friday"],
  "schedule_time": "08:00",
  "color": "#22c55e",
  "notes": "Start from station, work north"
}
Response β€” 201 Created
JSON
{
  "route": {
    "id": "route-uuid-001",
    "name": "Shibuya Morning Route",
    "area_name": "Shibuya",
    "country_code": "JP",
    "schedule_days": ["monday", "wednesday", "friday"],
    "schedule_time": "08:00",
    "color": "#22c55e",
    "notes": "Start from station, work north",
    "created_at": "2026-04-14T09:00:00Z"
  }
}
GET /api/dispatch/routes List routes β–Ύ

Returns all collection routes.

Response β€” 200 OK
JSON
{
  "routes": [
    {
      "id": "route-uuid-001",
      "name": "Shibuya Morning Route",
      "area_name": "Shibuya",
      "schedule_days": ["monday", "wednesday", "friday"],
      "schedule_time": "08:00",
      "color": "#22c55e",
      "stop_count": 8,
      "created_at": "2026-04-14T09:00:00Z"
    }
  ]
}
GET /api/dispatch/routes/{id} Get route with stops β–Ύ

Returns a single route including its ordered list of stops (collection points).

Response β€” 200 OK
JSON
{
  "route": {
    "id": "route-uuid-001",
    "name": "Shibuya Morning Route",
    "area_name": "Shibuya",
    "country_code": "JP",
    "schedule_days": ["monday", "wednesday", "friday"],
    "schedule_time": "08:00",
    "color": "#22c55e",
    "notes": "Start from station, work north",
    "stops": [
      {
        "order": 1,
        "collection_point": {
          "id": "cp-uuid-001",
          "name": "Shibuya Station Drop-off",
          "address": "2-24-12 Shibuya, Shibuya-ku, Tokyo",
          "latitude": 35.6580,
          "longitude": 139.7016
        }
      },
      {
        "order": 2,
        "collection_point": {
          "id": "cp-uuid-003",
          "name": "Harajuku Office Building",
          "address": "1-1-1 Jingumae, Shibuya-ku, Tokyo",
          "latitude": 35.6702,
          "longitude": 139.7027
        }
      }
    ],
    "created_at": "2026-04-14T09:00:00Z"
  }
}
PUT /api/dispatch/routes/{id} Update route β–Ύ

Update route metadata. Accepts the same fields as create (name, area_name, country_code, schedule_days, schedule_time, color, notes).

Request Body
JSON
{
  "name": "Shibuya Morning Route (Revised)",
  "schedule_days": ["monday", "tuesday", "thursday"],
  "schedule_time": "07:30"
}
Response β€” 200 OK
JSON
{
  "route": {
    "id": "route-uuid-001",
    "name": "Shibuya Morning Route (Revised)",
    "schedule_days": ["monday", "tuesday", "thursday"],
    "schedule_time": "07:30",
    "...": "..."
  }
}
DELETE /api/dispatch/routes/{id} Delete route β–Ύ

Permanently delete a route and its stop associations.

Response β€” 200 OK
JSON
{
  "message": "route deleted"
}
POST /api/dispatch/routes/{id}/clone Clone route β–Ύ

Create a copy of an existing route including all its stops. The cloned route name is suffixed with " (Copy)".

Response β€” 201 Created
JSON
{
  "route": {
    "id": "route-uuid-002",
    "name": "Shibuya Morning Route (Copy)",
    "area_name": "Shibuya",
    "schedule_days": ["monday", "wednesday", "friday"],
    "stops": [ ... ],
    "created_at": "2026-04-14T12:00:00Z"
  }
}
PUT /api/dispatch/routes/{id}/stops Set route stops β–Ύ

Replace the ordered list of stops for a route. Each stop references a collection point and has an explicit order.

Request Body
JSON
{
  "stops": [
    { "collection_point_id": "cp-uuid-001", "order": 1 },
    { "collection_point_id": "cp-uuid-003", "order": 2 },
    { "collection_point_id": "cp-uuid-005", "order": 3 }
  ]
}
Response β€” 200 OK
JSON
{
  "route": {
    "id": "route-uuid-001",
    "stops": [
      { "order": 1, "collection_point": { "id": "cp-uuid-001", "name": "Shibuya Station Drop-off" } },
      { "order": 2, "collection_point": { "id": "cp-uuid-003", "name": "Harajuku Office Building" } },
      { "order": 3, "collection_point": { "id": "cp-uuid-005", "name": "Yoyogi Park Bins" } }
    ]
  }
}
POST /api/dispatch/routes/{id}/optimize Optimize stop order β–Ύ

Automatically reorder the route's stops to minimize total travel distance.

Response β€” 200 OK
JSON
{
  "route": {
    "id": "route-uuid-001",
    "name": "Shibuya Morning Route",
    "stops": [
      { "order": 1, "collection_point": { "id": "cp-uuid-003", "name": "Harajuku Office Building" } },
      { "order": 2, "collection_point": { "id": "cp-uuid-005", "name": "Yoyogi Park Bins" } },
      { "order": 3, "collection_point": { "id": "cp-uuid-001", "name": "Shibuya Station Drop-off" } }
    ]
  }
}

Dispatch: Route Scheduling

Schedule routes for specific dates and assign drivers. Generate daily schedules from route templates. Dispatch

GET /api/dispatch/route-assignments List route assignments β–Ύ

Returns route assignments for a given date, including assigned drivers and completion status.

Query Parameters
ParamTypeDescription
datestringDate to query (YYYY-MM-DD, default today)
Response β€” 200 OK
JSON
{
  "assignments": [
    {
      "id": "ra-uuid-001",
      "route_id": "route-uuid-001",
      "route_name": "Shibuya Morning Route",
      "driver_id": "driver-uuid",
      "driver_name": "Tanaka Yuki",
      "date": "2026-01-15",
      "status": "pending",
      "created_at": "2026-01-14T18:00:00Z"
    }
  ]
}
PUT /api/dispatch/route-assignments/{id} Update route assignment β–Ύ

Assign or reassign a driver to a route assignment, or update its status.

Request Body
JSON
{
  "driver_id": "driver-uuid",
  "status": "in_progress"
}
Response β€” 200 OK
JSON
{
  "assignment": {
    "id": "ra-uuid-001",
    "route_id": "route-uuid-001",
    "driver_id": "driver-uuid",
    "status": "in_progress"
  },
  "message": "assignment updated"
}
DELETE /api/dispatch/route-assignments/{id} Delete route assignment β–Ύ

Remove a route assignment. The route itself is not affected.

Response β€” 200 OK
JSON
{
  "message": "assignment deleted"
}
POST /api/dispatch/routes/generate-schedule Generate daily schedule β–Ύ

Generate route assignments for a specific date based on each route's schedule_days configuration. Routes whose schedule includes the target day-of-week will have assignments created.

Request Body
JSON
{
  "date": "2026-01-15"
}
Response β€” 200 OK
JSON
{
  "created": 5,
  "date": "2026-01-15",
  "assignments": [
    {
      "id": "ra-uuid-010",
      "route_id": "route-uuid-001",
      "route_name": "Shibuya Morning Route",
      "date": "2026-01-15T00:00:00Z",
      "status": "scheduled",
      ...
    }
  ],
  "message": "Generated 5 assignments for 2026-01-15 (Thu)"
}

Only active routes; a route already on the date is skipped; assignments lists all of the date's entries. A past date is refused.

POST /api/dispatch/routes/auto-assign Auto-assign drivers to routes β–Ύ

Plans which online driver (with a known location) takes which of a date's schedule entries with no driver, by the distance to each route's first stop, and saves it only with "commit": true. Body: { "date": "2026-09-15", "commit": false }; a past date is refused.

Response β€” 200 OK
JSON
{
  "assignments": [
    { "assignment_id": "ra_001", "route_name": "Shibuya Morning", "driver_id": "usr_d001",
      "driver_name": "Kenji Yamada", "distance_to_start_km": 2.4, "stop_count": 8 }
  ],
  "date": "2026-09-15",
  "committed": 0,
  "dry_run": true,
  "message": "Preview only. Set commit=true to apply."
}

Admin: Users

Manage platform users, roles, and access. Admin

GET /api/admin/users List all users β–Ύ
Response β€” 200 OK
JSON
{
  "users": [
    {
      "id": "user-uuid",
      "email": "driver@getgomi.xyz",
      "first_name": "Tanaka",
      "last_name": "Yuki",
      "role": "driver",
      "status": "online",
      "created_at": "2026-01-15T00:00:00Z",
      "last_login_at": "2026-04-14T08:00:00Z"
    }
  ],
  "total": 24
}
GET /api/admin/users/{id} Get user detail β–Ύ

Returns full user profile including activity history summary.

PATCH /api/admin/users/{id}/role Change user role β–Ύ
Request Body
JSON
{
  "role": "dispatcher"
}

Valid roles: driver, dispatcher, admin. Sets the role in the active company only.

PATCH /api/admin/users/{id}/status Change user status β–Ύ
Request Body
JSON
{
  "status": "offline"
}

Valid statuses: offline, online, on_job. To stop someone signing in, a super admin disables the account (POST /api/super/users/{id}/disable).

Admin: Invites

POST /api/admin/invites Send invite β–Ύ
Request Body
JSON
{
  "email": "newdriver@example.com",
  "role": "driver"
}
Response β€” 201 Created
JSON
{
  "invite": {
    "id": "invite-uuid",
    "email": "newdriver@example.com",
    "role": "driver",
    "invited_by": "admin-uuid",
    "created_at": "2026-04-14T10:00:00Z",
    "expires_at": "2026-04-21T10:00:00Z"
  }
}
GET /api/admin/invites List invites β–Ύ

Returns all pending and expired invites.

DELETE /api/admin/invites/{id} Revoke invite β–Ύ

Revokes a pending invite so it can no longer be used.

Admin: Photo Search

GET /api/admin/photos Search all job photos β–Ύ

Search and filter photos across all jobs and drivers. Returns EXIF metadata, driver info, and job title.

Query Parameters
ParamTypeDescription
job_idstringFilter by job ID
driver_idstringFilter by driver ID
phasestringbefore or after
taken_afterISO 8601EXIF date lower bound
taken_beforeISO 8601EXIF date upper bound
pageintPage number (default 1)
limitintResults per page (default 50)
Example
# All photos by Harold from last week
GET /api/admin/photos?driver_id=c88d57e3&taken_after=2026-06-30T00:00:00Z

# All completion photos for a specific job
GET /api/admin/photos?job_id=abc123&phase=after
Response β€” 200 OK
JSON
{
  "photos": [
    {
      "id": "a1b2c3d4...",
      "job_id": "c88d57e3...",
      "job_title": "Shibuya pickup",
      "driver_id": "d9f8e7c6...",
      "driver_first_name": "Kenji",
      "driver_last_name": "Yamada",
      "driver_email": "kenji@example.com",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/...",
      "exif_taken_at": "2026-07-07T10:30:00Z",
      "exif_lat": -1.2861,
      "exif_lng": 36.8172,
      "exif_make": "Samsung",
      "exif_model": "Galaxy S24",
      "size_bytes": 4521983,
      "uploaded_at": "2026-07-07T10:31:15Z"
    }
  ]
}

Admin: Audit & Keys

GET /api/admin/audit/auth Auth audit log β–Ύ

Returns authentication events (login, logout, key usage) for all users.

Response β€” 200 OK
JSON
{
  "events": [
    {
      "id": "evt-uuid",
      "user_id": "user-uuid",
      "email": "driver@getgomi.xyz",
      "event_type": "login",
      "ip_address": "203.0.113.42",
      "user_agent": "Mozilla/5.0 ...",
      "created_at": "2026-04-14T08:00:00Z"
    }
  ],
  "total": 1502
}
GET /api/admin/keys List all API keys β–Ύ

Returns all API keys across all users. Admins can see key metadata but not raw key values.

DELETE /api/admin/keys/{id} Revoke any API key β–Ύ

Admins can revoke any user's API key. The key is immediately invalidated.

POST /api/admin/users/{id}/create-key Create API key for any user β–Ύ

Admins can create an API key on behalf of any user. The raw key is returned only once β€” store it securely.

Response β€” 201 Created
JSON
{
  "key": "gomi_d0ea77fe9a3b4c1e8f2d6a7b5c0e1f3a",
  "id": "key-uuid-001",
  "prefix": "gomi_d0ea",
  "user_id": "user-uuid",
  "user_name": "Tanaka Yuki"
}

Reference: Waste Types

Public

GET /api/waste-types List waste types β–Ύ
Response β€” 200 OK
JSON
{
  "waste_types": [
    {
      "id": "wt-uuid-001",
      "name": "Burnable",
      "name_local": "η‡ƒγˆγ‚‹γ‚΄γƒŸ",
      "color": "#ef4444",
      "icon": "πŸ”₯",
      "country_code": "JP"
    },
    {
      "id": "wt-uuid-002",
      "name": "Recyclable",
      "name_local": "θ³‡ζΊγ‚΄γƒŸ",
      "color": "#3b82f6",
      "icon": "♻️",
      "country_code": "JP"
    },
    {
      "id": "wt-uuid-003",
      "name": "Non-Burnable",
      "name_local": "η‡ƒγˆγͺγ„γ‚΄γƒŸ",
      "color": "#6b7280",
      "icon": "πŸͺ¨",
      "country_code": "JP"
    },
    {
      "id": "wt-uuid-004",
      "name": "Oversized",
      "name_local": "η²—ε€§γ‚΄γƒŸ",
      "color": "#f59e0b",
      "icon": "πŸ“¦",
      "country_code": "JP"
    }
  ]
}

Status Flows

User Status

offline β†’ online β†’ on_job β†’ online β†’ offline

Job Status

pending β†’ assigned β†’ in_progress β†’ completed

Trip Status

en_route β†’ arrived β†’ completed

Or from any state β†’ cancelled

Error Handling

All errors return a consistent JSON structure with an appropriate HTTP status code:

Error Response
{
  "error": "Human-readable error message"
}
StatusMeaningExample
400Bad RequestMissing required field, invalid format
401UnauthorizedMissing or invalid API key / session
403ForbiddenInsufficient role (driver accessing admin endpoint)
404Not FoundResource doesn't exist
409ConflictAlready clocked in, trip already active
500Server ErrorInternal server error
Error Handling Example
try {
  await api('/api/driver/clock-in', {
    method: 'PUT',
    body: JSON.stringify({ latitude: 35.68, longitude: 139.77 }),
  });
} catch (err) {
  if (err.message === 'already clocked in') {
    // Handle 409 conflict
    console.log('Driver is already on shift');
  } else {
    console.error('Clock-in failed:', err.message);
  }
}

Health Check

GET /health Service health β–Ύ

Public endpoint for monitoring. No authentication required.

Response β€” 200 OK
JSON
{
  "status": "ok"
}

Gomi API Documentation β€” Built for waste collection in Japan πŸ‡―πŸ‡΅

Β© 2026 getgomi.xyz

acbe83d