60 lines
8.0 KiB
Markdown
60 lines
8.0 KiB
Markdown
# TaskNest Food and Kitchen API v1
|
||
|
||
The API is available under `/api/v1/`; machine-readable OpenAPI 3.1 is at `/api/v1/schema/`. The MCP server uses these endpoints. There is no interactive production API UI.
|
||
|
||
## Authentication and permissions
|
||
|
||
Create a personal token in Settings → API access. The full `tn_...` token is shown once. Send it as `Authorization: Bearer <token>`. A token identifies its owner; API requests do not accept a user identifier. Tokens can have `food:read`, `food:write`, `inventory:read`, and `inventory:write`. A missing, invalid, revoked, or expired token returns HTTP 401. A missing scope returns HTTP 403. The token management screen supports optional expiry and revocation. HTTPS is required in deployment to protect bearer tokens in transit.
|
||
|
||
Each resource lookup filters by the token owner. An unknown UUID and another user's UUID both return 404. The API does not use session authentication, and its bearer-token views are CSRF exempt. Default Django CORS policy does not grant cross-origin browser access. Do not log `Authorization` headers.
|
||
|
||
## Endpoints
|
||
|
||
| Method | Route | Scope | Purpose |
|
||
| --- | --- | --- | --- |
|
||
| GET | `/food/today/` | `food:read` | User-local date, entries grouped by meal, seven daily totals, and existing goals |
|
||
| GET | `/food/products/?search=&limit=30&offset=0` | `food:read` | Own products, nutrition per 100, and portions; no `raw_data` |
|
||
| POST | `/food/log/` | `food:write` | Create from an owned `product_id` or manual snapshot |
|
||
| GET/PATCH/DELETE | `/food/log/{id}/` | read/write | Own log entry |
|
||
| POST | `/food/log/{id}/attachments/` | `food:write` | Multipart image upload to an owned entry |
|
||
| GET | `/food/attachments/{id}/file/` | `food:read` | Authenticated image retrieval |
|
||
| DELETE | `/food/attachments/{id}/` | `food:write` | Delete an owned image |
|
||
| GET/POST | `/kitchen/items/` | read/write | Search/list or create inventory item |
|
||
| GET/PATCH/DELETE | `/kitchen/items/{id}/` | read/write | Own inventory item |
|
||
| GET | `/hydration/daily/?date=YYYY-MM-DD` | `food:read` | Combined total, manual and Food Diary contributions, goal, and remaining amount |
|
||
| POST | `/hydration/manual/` | `food:write` | Standalone fluid entry; optional `Idempotency-Key` |
|
||
| PATCH/DELETE | `/hydration/manual/{id}/` | `food:write` | Correct or remove an owned manual fluid entry |
|
||
| GET/PATCH | `/hydration/settings/` | read/write | Automatic counting, liquid foods, breakdown, manual adjustments, and beverage rules |
|
||
|
||
Collection responses use `count`, `limit`, `offset`, and `results`. The default limit is 30 and maximum is 100; `offset` is capped at 10,000. Product and inventory search checks name, brand, and barcode; inventory search also checks location and category. `GET /food/today/` is naturally bounded by one day.
|
||
|
||
JSON decimal values are strings to preserve precision. For food creation, send `meal`, positive decimal `amount`, and `unit` (`g` or `ml`). With `product_id`, nutrition and name snapshots are calculated from that owned product using the same service as the web UI, and the unit must match its basis. Without a product, send `product_name` and optional `brand`, `barcode`, `portion_label`, and nutrition totals (`calories_kcal`, `carbohydrates_g`, `protein_g`, `fat_g`, `fibre_g`, `sugars_g`, `salt_g`). Manual entries are snapshot-only, so repeat estimates do not create duplicate products. `date` defaults to the user's saved local time zone date; an explicit ISO date and optional time can be supplied. API entries have `created_via: api`, separate from their nutrition `source`.
|
||
|
||
Inventory creation requires an owned product UUID, positive integer `quantity` (outer package count), and a location name. Optional fields include `category`, `notes`, `opened`, and `best_before`. Flat packages may supply `original_amount` and `unit`, `pieces_per_package`, `remaining_pieces`, and explicit `piece_amount`. For one nested layer, supply `inner_packs_per_package`, `pieces_per_inner_pack`, `inner_pack_label`, `piece_label`, and (for measured stock) `inner_pack_amount`; `original_amount` is derived as inner-pack amount × inner-pack count. Total pieces are derived from the two counts. For example, 6 inner packs × 3 biscuits with 44 g per inner pack creates one 264 g package with 18 pieces. Per-biscuit weight is an estimate derived from the measured inner-pack amount. With no measured amount, nested piece contents use `pieces` as the stock unit. Location and category names reuse the application's owned lookup records. DELETE removes the item, matching the API operation; the web inventory still has its separate archive behavior.
|
||
|
||
For attachment upload, send multipart `image` and optional `caption`. JPEG, PNG, and WebP are accepted after decoding and format/MIME checks. The file limit is 5 MiB and the pixel limit is 25 million. Images are stored under `main/private_media/`, which has no public media URL; download requires `food:read` and ownership of the parent entry. Filenames on disk are random. The original filename is metadata only.
|
||
|
||
POST creation routes accept an optional `Idempotency-Key` header. Repeating the same token, route, key, and body returns the stored result and creates no second record. Reusing a key with a different body or route returns 409. Keys are per token. JSON errors use `{"error":{"code":"...","message":"..."}}`; validation may include `details`. Common codes include `invalid_token`, `expired_token`, `insufficient_scope`, `entry_not_found`, `product_not_found`, `inventory_item_not_found`, `image_too_large`, and `unsupported_image_type`.
|
||
|
||
## Hydration accounting
|
||
|
||
Food Diary entries saved in millilitres can count toward hydration automatically. Each entry stores its eligible volume, counting factor, and classification source, so later product edits do not rewrite past totals. Grams are never converted to millilitres. Soup counting is off by default. Users can override a product's drink classification from the Food Diary. Manual entry timestamps use the user's local date; food contributions use the Food Diary date. Web and API food logging use the same calculation, so clients do not need a second hydration call.
|
||
|
||
For a packaged inventory item, `PATCH /kitchen/items/{id}/` may set `remaining_amount` to an absolute value from zero through its current remaining amount. A reduction uses the existing inventory consumption service; zero archives that package from active inventory. `opened`, `notes`, and other metadata can be sent in the same request. Increasing stock or exceeding the package capacity is rejected. Quantity validation errors return `error.details.field` and `error.details.reason`.
|
||
|
||
For piece-aware stock, `PATCH` may instead set absolute `remaining_pieces`; a reduction consumes the difference atomically and updates measured stock and opened state. Do not send both remaining fields in one request. Flat piece-to-mass or piece-to-volume conversion requires an explicit `piece_amount`. Nested packages derive piece estimates from the explicit `inner_pack_amount`; measured deductions must correspond to whole pieces, and the final piece consumes the exact remaining residual. Consumption accepts `inner_packs` for configured nested packages. Inventory responses include the inner-pack counts, labels, and derived opened-inner-pack remainder. A count-only legacy row can be converted in place by supplying `quantity` explicitly with package contents and, when needed, measured amount and unit. Historical food logs are untouched.
|
||
|
||
## Example requests
|
||
|
||
```sh
|
||
TOKEN='<token-shown-once-in-settings>'
|
||
curl -H "Authorization: Bearer $TOKEN" https://example.com/api/v1/food/today/
|
||
curl -H "Authorization: Bearer $TOKEN" 'https://example.com/api/v1/food/products/?search=pasta'
|
||
curl -X POST https://example.com/api/v1/food/log/ \
|
||
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
|
||
-H 'Idempotency-Key: dinner-2026-10-07-1' \
|
||
-d '{"meal":"dinner","product_name":"Homemade satay","amount":"1","unit":"g","calories_kcal":"850"}'
|
||
curl -X POST https://example.com/api/v1/food/log/ENTRY_UUID/attachments/ \
|
||
-H "Authorization: Bearer $TOKEN" -F 'image=@meal.jpg;type=image/jpeg' -F 'caption=Dinner'
|
||
```
|