# Teamward API

Teamward's REST API lets your own systems read and update your Teamward account: staff, the time clock and
timesheets, time off, chat, the company feed, the knowledge base and HR records. Webhooks push events (a clock-in,
a time off request, a new hire) to your system the moment they happen.

It is modelled on Connecteam's API, so if you have an integration for Connecteam most of it carries over: the same
`X-API-KEY` header, the same `/area/v1/...` paths, `limit`/`offset` paging, a `{requestId, data, paging}` response
envelope, Unix-second timestamps, `x-ratelimit-*` headers and webhooks with an `x-webhook-secret` header.

## Getting started

1. In Teamward, an **admin** opens **Office Admin → API & webhooks → Create key**, names it after the system it's
   for, and ticks the permissions it needs. The key (`tw_live_…`) is shown once. Copy it somewhere safe.
2. Call the API with the key in the `X-API-KEY` header:

```bash
curl https://api.teamward.app/me -H "X-API-KEY: tw_live_your_key_here"
```

Base URL: `https://api.teamward.app`. Until that address is live for you, the same API answers at `https://vecnqjyejqxluxookmnb.supabase.co/functions/v1/api`.

## How keys work

- A key belongs to one company and acts **on behalf of the admin who created it**. Everything it does follows that
  admin's access rules and shows up in Teamward as done by them (or, for punches, by the employee being punched).
- A key only reaches the areas you ticked (its *scopes*). Calling something outside them returns `403`.
- A key stops working if it's revoked, if the admin who made it is removed or is no longer an admin, or if the
  Teamward account is locked for billing.
- Make one key per connected system so you can revoke one without breaking the others. Keys are stored scrambled
  (hashed); Teamward can't show a key again after it's created.

| Scope | Gives |
| --- | --- |
| `users.read` / `users.write` | Staff, roles, branches / add, change, archive and restore staff |
| `time_clock.read` / `time_clock.write` | Shifts, punches, requests, timesheet totals / clock in/out, breaks, add/edit/delete shifts, review requests |
| `time_off.read` / `time_off.write` | Requests, types, balances, holidays / book, approve, deny, cancel |
| `chat.read` / `chat.write` | The key owner's conversations and messages / send messages as the key owner |
| `feed.read` / `feed.write` | Company feed posts / publish posts |
| `kb.read` | Published knowledge base articles |
| `hr.read` | HR records: pay rate, hire date, birthday, address, emergency contact, licences. Also adds pay rate and estimated gross pay to timesheet totals |
| `webhooks.read` / `webhooks.write` | List / create, change, test and delete webhooks |

## Requests and responses

- JSON in and out. Send `Content-Type: application/json` with a body.
- IDs are UUID strings (Connecteam uses integers, so store them as text).
- Timestamps are **Unix seconds**. Dates are `YYYY-MM-DD` and times `HH:MM` (24-hour), in the company's time zone
  (`GET /me` returns it).
- Every response has a `requestId`. Successful ones put the result in `data`:

```json
{ "requestId": "3f0c…", "data": { "users": [ … ] }, "paging": { "offset": 10, "total": 37 } }
```

## Paging

List endpoints take `limit` (1–500, default 10) and `offset` (default 0). `paging.offset` is the offset to ask for
next and `paging.total` the number of matches. Stop when a page has fewer items than `limit`:

```python
offset, users = 0, []
while True:
    r = requests.get(f"https://api.teamward.app/users/v1/users", params={"limit": 500, "offset": offset},
                     headers={"X-API-KEY": KEY}).json()
    users += r["data"]["users"]
    if len(r["data"]["users"]) < 500: break
    offset = r["paging"]["offset"]
```

## Rate limits

100 requests a minute and 10,000 a day **per company** (shared by all its keys). Every response carries
`x-ratelimit-minute-limit`, `x-ratelimit-minute-remaining`, `x-ratelimit-minute-reset`, `x-ratelimit-day-limit`,
`x-ratelimit-day-remaining` and `x-ratelimit-day-reset` (reset = Unix seconds). Over the limit you get `429` with a
`Retry-After` header. Back off and retry.

## Errors

Errors carry a `detail`. Validation errors (`422`) list each problem, like Connecteam:

```json
{ "requestId": "…", "detail": [{ "loc": ["query", "startDate"], "msg": "Use YYYY-MM-DD", "type": "value_error" }] }
```

| Status | Meaning |
| --- | --- |
| 400 | Teamward refused the change (the message says why, e.g. "This request was already reviewed") |
| 401 | Missing, wrong or revoked key, or its admin was removed |
| 403 | The key lacks the scope, the key owner isn't allowed, or the account is locked |
| 404 | Not found (or not visible to the key owner) |
| 409 | Conflicts with existing data (overlapping shift, already clocked in, email already used) |
| 422 | Invalid input |
| 429 | Rate limit, see above |
| 500 | Our fault. Retry later and quote the `requestId` if it keeps happening |

## The time clock

Each company has one time clock. Its ID is your company ID (from `GET /me`), and the word `default` works
everywhere a `timeClockId` is expected. A shift (`timeActivity`) has a `start` and `end` time point (`timestamp`,
`timezone`, optional `locationData`), `breakMinutes`, `workedMinutes` and `isOpen` while the person is still clocked in.
Teamward records breaks as total minutes on the shift, so `manualBreaks` is always empty.

`GET …/timesheet` returns pay-period totals calculated exactly like Teamward's payroll page: regular and overtime hours
per Monday–Sunday week (your overtime rules), public holiday pay, holiday premium hours and paid/unpaid time off.

## Webhooks

Create webhooks in **Office Admin → API & webhooks**, or with `POST /settings/v1/webhooks`. Teamward sends a `POST`
with a JSON body to your HTTPS URL for each event you subscribed to (or `["*"]` for all).

- Headers: `x-webhook-secret` (the webhook's secret, shown once when it's created. Compare it to make sure the
  call came from Teamward), `x-teamward-event` and `x-teamward-delivery` (a delivery ID).
- Reply with any `2xx` within **10 seconds**, then do the slow work afterwards.
- Failed deliveries are retried up to 3 more times (after about 1, 4 and 9 minutes). `404` is treated as permanent.
  A webhook that fails 50 times in a row is switched off; turn it back on in Teamward.
- Retries resend the same body. Deduplicate on `x-teamward-delivery`, or on `eventType` plus the entity ID.

Every payload has `requestId`, `company`, `eventType`, `eventTimestamp`, `activityType` and `webhookVersion` (1).
Time clock events are flat like Connecteam's (`userId`, `timeClockId`, `timeActivityId`, `timeActivity`, `actorId`).
The others put the record in `data`.

```json
{ "requestId": "…", "company": "<companyId>", "eventType": "clock_in", "eventTimestamp": 1793700000,
  "activityType": "shift", "webhookVersion": 1, "userId": "…", "timeClockId": "<companyId>",
  "timeActivityId": "…", "actorId": "…",
  "timeActivity": { "id": "…", "userId": "…", "start": { "timestamp": 1793700000, "timezone": "America/Toronto" },
                    "breakMinutes": 0, "workedMinutes": 0, "isOpen": true } }
```

| Area | activityType | eventType |
| --- | --- | --- |
| Staff | `User` | `user_created`, `user_updated`, `user_archived`, `user_restored` (data = array of users) |
| Time clock | `shift` | `clock_in`, `clock_out`, `break_start`, `break_end`, `admin_add`, `admin_edit`, `admin_delete`, `user_add_request`, `user_edit_request`, `user_delete_request`, `admin_approved_add_request`, `admin_approved_edit_request`, `admin_approved_delete_request`, `admin_declined_request` |
| Time off | `time_off` | `time_off_requested`, `time_off_booked`, `time_off_approved`, `time_off_denied`, `time_off_cancelled` |
| Chat | `chat` | `message_created`, `message_updated`, `message_deleted` |
| Feed | `feed` | `post_published` |
| Test | `webhook` | `ping` (from the Test button or `POST /settings/v1/webhooks/{id}/test`) |

## Coming from Connecteam

| Connecteam | Teamward |
| --- | --- |
| `GET /me` | `GET /me` (adds `timezone` and the key's scopes) |
| `GET /users/v1/users` | same, plus `branchIds`/`roleIds` filters |
| `POST /users/v1/users` (array) | same (people get an email invite to set their password) |
| Smart groups | Roles (`/users/v1/roles`) and branches (`/users/v1/branches`) |
| `GET /time-clock/v1/time-clocks` | same (one clock per company) |
| `GET /time-clock/v1/time-clocks/{id}/time-activities` | same shape: `timeActivitiesByUsers[].shifts/manualBreaks/timeOffs` |
| Clock in / out | `POST …/clock-in`, `…/clock-out`, `…/break-start`, `…/break-end` |
| `GET /time-off/v1/requests`, policy types, balances | same paths |
| `GET /chat/v1/conversations`, `POST …/{id}/message` | same (as the key owner) |
| Webhooks (`/settings/v1/webhooks`, `x-webhook-secret`) | same |
| Job scheduling, tasks, forms, jobs | Not in Teamward yet |

## Endpoints


### Account

- **GET `/me`**: Get account information. Your company, its time zone and what this key can do. A good first call to check a key.

### Users

- **GET `/users/v1/users`**: Get users (scope `users.read`). Query: `limit`, `offset`, `userIds`, `userStatus`, `emailAddresses`, `fullNames`, `phoneNumbers`, `branchIds`, `roleIds`, `createdAt`, `modifiedAt`, `lastLogin`, `sort`, `order`
- **POST `/users/v1/users`**: Create users (scope `users.write`). Adds 1–50 people to your company. Each gets an email invite to choose a password. People with no `roleId` get your default technician role. `409` if an email already has a Teamward login.
- **GET `/users/v1/users/{userId}`**: Get a user (scope `users.read`)
- **PUT `/users/v1/users/{userId}`**: Update a user (scope `users.write`). Only the fields you send change. Email can't be changed here (people change it themselves).
- **POST `/users/v1/users/archive`**: Archive users (scope `users.write`). Turns off sign-in for these people (the same as switching off *Can sign in*). Their history stays.
- **POST `/users/v1/users/restore`**: Restore users (scope `users.write`)
- **GET `/users/v1/roles`**: Get roles (scope `users.read`)
- **GET `/users/v1/branches`**: Get branches (scope `users.read`)

### Time clock

- **GET `/time-clock/v1/time-clocks`**: Get time clocks (scope `time_clock.read`)
- **GET `/time-clock/v1/time-clocks/{timeClockId}/time-activities`**: Get time activities (scope `time_clock.read`). Query: `startDate`*, `endDate`*, `userIds`. Shifts that started in the date range (company time zone, up to 366 days) and approved time off overlapping it, grouped by person. `/time-clock/v1/time-activities` is a shortcut for the default clock.
- **POST `/time-clock/v1/time-clocks/{timeClockId}/time-activities`**: Add shifts (scope `time_clock.write`). Adds finished shifts, the same as a manager adding one in the app. They're marked manual and logged in the punch log. Shifts can't overlap, be in the future or be longer than 24 hours.
- **PUT `/time-clock/v1/time-clocks/{timeClockId}/time-activities/{activityId}`**: Edit a shift (scope `time_clock.write`)
- **DELETE `/time-clock/v1/time-clocks/{timeClockId}/time-activities/{activityId}`**: Delete a shift (scope `time_clock.write`)
- **POST `/time-clock/v1/time-clocks/{timeClockId}/clock-in`**: Clock in (scope `time_clock.write`). Punches for an employee, e.g. from a kiosk or another system. Recorded as the employee's own punch. `409` if they're already in that state.
- **POST `/time-clock/v1/time-clocks/{timeClockId}/clock-out`**: Clock out (scope `time_clock.write`). Punches for an employee, e.g. from a kiosk or another system. Recorded as the employee's own punch. `409` if they're already in that state.
- **POST `/time-clock/v1/time-clocks/{timeClockId}/break-start`**: Start a break (scope `time_clock.write`). Punches for an employee, e.g. from a kiosk or another system. Recorded as the employee's own punch. `409` if they're already in that state.
- **POST `/time-clock/v1/time-clocks/{timeClockId}/break-end`**: End a break (scope `time_clock.write`). Punches for an employee, e.g. from a kiosk or another system. Recorded as the employee's own punch. `409` if they're already in that state.
- **GET `/time-clock/v1/time-clocks/{timeClockId}/on-the-clock`**: Who's clocked in (scope `time_clock.read`)
- **GET `/time-clock/v1/time-clocks/{timeClockId}/punches`**: Get the punch log (scope `time_clock.read`). Query: `startDate`*, `endDate`*, `userIds`, `limit`, `offset`. Every punch and edit, with who made it.
- **GET `/time-clock/v1/time-clocks/{timeClockId}/requests`**: Get shift change requests (scope `time_clock.read`). Query: `limit`, `offset`, `userIds`, `statuses`. Employees' requests to add, change or delete a shift.
- **POST `/time-clock/v1/time-clocks/{timeClockId}/requests/{requestId}/approve`**: Approve a shift request (scope `time_clock.write`)
- **POST `/time-clock/v1/time-clocks/{timeClockId}/requests/{requestId}/decline`**: Decline a shift request (scope `time_clock.write`)
- **GET `/time-clock/v1/time-clocks/{timeClockId}/timesheet`**: Get timesheet totals (scope `time_clock.read`). Query: `startDate`*, `endDate`*, `userIds`. Pay-period totals, the same as Teamward's payroll page. The range is widened to whole Monday–Sunday weeks (up to 9 weeks). Overtime, public holiday pay and premium follow your payroll rules.

### Time off

- **GET `/time-off/v1/policy-types`**: Get time off types (scope `time_off.read`)
- **GET `/time-off/v1/requests`**: Get time off requests (scope `time_off.read`). Query: `limit`, `offset`, `userIds`, `startDate`, `endDate`, `statuses`
- **POST `/time-off/v1/requests`**: Book time off (scope `time_off.write`). Books time off for someone, approved straight away (like a manager booking it). The person is notified.
- **GET `/time-off/v1/requests/{requestId}`**: Get a time off request (scope `time_off.read`)
- **POST `/time-off/v1/requests/{requestId}/approve`**: Approve a pending request (scope `time_off.write`)
- **POST `/time-off/v1/requests/{requestId}/deny`**: Deny a pending request (scope `time_off.write`)
- **POST `/time-off/v1/requests/{requestId}/cancel`**: Cancel a request (scope `time_off.write`)
- **GET `/time-off/v1/balances`**: Get balances (scope `time_off.read`). Query: `limit`, `offset`, `userIds`
- **GET `/time-off/v1/holidays`**: Get public holidays (scope `time_off.read`). Query: `year`

### Chat

- **GET `/chat/v1/conversations`**: Get conversations (scope `chat.read`). Query: `limit`, `offset`. The conversations the key owner is in. Chat is private, so the API can't see chats the key owner isn't part of.
- **GET `/chat/v1/conversations/{conversationId}/messages`**: Get messages (scope `chat.read`). Query: `limit`, `offset`, `since`, `order`
- **POST `/chat/v1/conversations/{conversationId}/message`**: Send a message (scope `chat.write`). Sent as the key owner.
- **POST `/chat/v1/users/{userId}/message`**: Send a private message (scope `chat.write`). A direct message from the key owner to one person. Opens the chat if needed.

### Feed

- **GET `/feed/v1/posts`**: Get posts (scope `feed.read`). Query: `limit`, `offset`, `since`
- **POST `/feed/v1/posts`**: Publish a post (scope `feed.write`). Posts to the company feed as the key owner. People are notified as usual.

### Knowledge base

- **GET `/kb/v1/articles`**: Get articles (scope `kb.read`). Query: `limit`, `offset`, `category`, `search`, `modifiedSince`
- **GET `/kb/v1/articles/{articleId}`**: Get an article (scope `kb.read`)

### HR

- **GET `/hr/v1/employees`**: Get HR records (scope `hr.read`). Query: `limit`, `offset`, `userIds`
- **GET `/hr/v1/certifications`**: Get licences and certifications (scope `hr.read`). Query: `limit`, `offset`, `userIds`, `expiringBefore`

### Webhooks

- **GET `/settings/v1/webhooks`**: Get webhooks (scope `webhooks.read`)
- **POST `/settings/v1/webhooks`**: Create a webhook (scope `webhooks.write`). The response includes `secretKey` once. Every delivery carries it in `x-webhook-secret`.
- **GET `/settings/v1/webhooks/event-types`**: Get event types (scope `webhooks.read`)
- **GET `/settings/v1/webhooks/{webhookId}`**: Get a webhook (scope `webhooks.read`)
- **PUT `/settings/v1/webhooks/{webhookId}`**: Update a webhook (scope `webhooks.write`)
- **DELETE `/settings/v1/webhooks/{webhookId}`**: Delete a webhook (scope `webhooks.write`)
- **POST `/settings/v1/webhooks/{webhookId}/test`**: Send a test event (scope `webhooks.write`)
- **GET `/settings/v1/webhooks/{webhookId}/deliveries`**: Get recent deliveries (scope `webhooks.read`). Query: `limit`, `offset`. The last 30 days of deliveries, newest first, with their payloads.

Full schemas: https://teamward.app/developers/openapi.json
