# API v1 — read-only foundation This is the read-only foundation of PN-5, not a complete mobile API. The public [API reference](https://pegboardnutrition.com/developers/api), machine-readable [OpenAPI 3.1 contract](https://pegboardnutrition.com/developers/api/openapi.json), and [this integration guide](https://pegboardnutrition.com/developers/api/guide.md) are hosted by Rails without a separate documentation service. The reference renders directly from the checked-in contract; automated response and public-documentation tests run in the existing Rails CI suite. ## Issue and revoke a token Sign in on the web, open **Profile → API access**, name the token, select 7, 30, 90, or 365 days, and confirm your current password. The secret appears **only in that immediate response**, never in a URL, flash/session cookie, later listing, or database column. Store it in a password manager or your client's secure credential store. The database stores a SHA-256 digest and a short non-secret hint. The creation form uses JavaScript to display the authenticated server response without adding a POST response to browser history; reloading returns to the ordinary list. JavaScript is needed to create a token through this UI, but not to view or revoke tokens. There may be at most ten active tokens per account. Revoke lost/exposed tokens in API access. Revocation is effective on subsequent requests and remains available after membership expiry. Expired/revoked tokens cannot be recovered or reactivated through the UI. Active tokens are listed ahead of the most recent 50 historical tokens. The only available scope is **journal:read**. It also grants read-only access to the shared reference-food and barcode previews described below. Token creation cannot request arbitrary scopes, owners, billing privileges, or non-expiring credentials. These personal tokens are **not** a finalized native-app login/refresh-token flow; do not ship a client asking users to paste tokens as a substitute for that work. ## Requests Production base URL: `https://pegboardnutrition.com/api/v1`. Send `Authorization: Bearer ` over HTTPS. Never put a real token in a query string, Git, screenshots, crash reports, or support messages. Browser login cookies alone do not authenticate this API, and there is no cross-origin browser permission. An environment-variable example avoids placing the actual token in shell history. Load the variable securely; do not paste its value into a saved script: ```sh curl --fail-with-body --silent --show-error \ --header "Authorization: Bearer $PEGBOARD_API_TOKEN" \ --header "Accept: application/json" \ "https://pegboardnutrition.com/api/v1/journal?date=2026-11-18" ``` Private API and token-management responses use `Cache-Control: no-store`. Clients must also avoid persisting private responses in shared caches. Parameter/authorization filtering covers API-token/password fields; do not enable custom logging that records bearer headers or response bodies. ## Implemented endpoints | GET path | Result | | --- | --- | | `/me` | Account ID, username, saved timezone, measurement preference, granted scope. No email, password digest, or provider identifiers. | | `/journal?date=YYYY-MM-DD` | Six meal slots, foods, precise daily/meal totals, and targets. Omitted date uses the owner's local date (UTC fallback). Reading an empty day creates nothing. | | `/macro_goal` | Daily macro/calorie targets, or `null`. Saved calculator inputs are not returned. | | `/food_logs` | Paginated food entries; optional `logged_on=YYYY-MM-DD` filter. | | `/food_logs/{id}` | One owned food entry. | | `/weight_entries` and `/weight_entries/{id}` | Paginated weight history or one entry, in pounds (`lb`). | | `/body_measurements` and `/body_measurements/{id}` | Paginated history or one entry in its **original** unit. Missing metrics remain `null`; saved display preferences do not rewrite measurements. | | `/food_library?q=eggs` | Reviewed USDA source records, verified portions, provenance, and catalog metadata. | | `/barcode_lookup?barcode=0012345678901` | One normalized Open Food Facts product preview, never an automatic journal save. | Single results use `{"data": ...}`. Journal-history lists additionally contain `pagination`: `page`, `per_page`, `has_more`, and nullable `next_page`. Default page size is 30; maximum is 100; pages are bounded to 1–10,000. Histories are ordered by date descending and then ID descending. This is offset pagination, not a snapshot: concurrent inserts/deletes can shift pages, so clients should deduplicate by ID and refresh as needed. Dates must be actual calendar dates in exact ISO `YYYY-MM-DD` form. Invalid dates, nested/array pagination inputs, negative pages, and oversized pages return 400. Ownership comes from the token, never a submitted `user_id`. ## Food previews Both lookups require the same valid bearer token and membership policy as journal reads. The catalog is shared, not private account data; no journal entries, meals, weights, or measurements are created or modified. These endpoints do not accept camera images or remote URLs. - `/food_library`: omitted/blank `q` returns up to 12 suggestions; a search returns at most 60 **source records**, not grouped display rows. Matching is the existing case-insensitive ASCII word-prefix search; fewer than two searchable characters returns no results. Unknown foods return an empty array. `q` must be a scalar string of at most 100 characters; oversized/nested/array inputs return 400 rather than silently truncating. This is a bounded search, not a paginated complete-catalog export. - The catalog envelope is `{"data":[...],"metadata":{...}}`. Metadata includes `catalog_version`, `source`, `source_verified_on`, `total_count` (all catalog source records), and `returned_count` (this response). Preserve distinct raw/cooked records; `group_id` lets clients combine variants visually without discarding `preparation`, `detail_name`, `log_name`, or exact portion weights. - Reference nutrition is per **100 g edible portion**, with protein/carbs/fat only. `servings` contains string IDs, labels, and decimal-string `grams`; `default_serving_id` selects one. Source URLs, descriptions, verification dates, and portion notes are retained. Calculate macro calories when the user chooses a portion; no cooked-weight, density, or package conversion is implied. - `/barcode_lookup`: required scalar `barcode` contains exactly 8, 12, 13, or 14 ASCII digits; keep leading zeros. Length/character validation is not a checksum or product-authenticity guarantee. Product nutrition is per 100 **g or mL**, identified by `unit`. Read `unit_inferred` before suggesting portions: true means the database did not identify the basis and the service's fallback is grams, **not a verified density**. Null serving quantities/units mean unknown, not one package or one serving. - Barcode `per_100` includes decimal-string label calories; `calories_derived` indicates whether missing label calories were calculated from macros. Preserve the user's subsequent edits/manual override. Never guess missing macros. Open Food Facts is community-supplied, not part of the reviewed USDA catalog; show the source and allow users to check/correct the package label. Treat names/labels as untrusted text, not HTML. - Barcode requests reuse the web service's successful-result cache (one day), bounded response size (1 MiB), fixed HTTPS host, no redirect following, and timeouts. A separate 30/minute/IP API barcode budget applies in addition to the shared 120/minute/IP API limit. Web route limits remain unchanged. ## Precision and compatibility - IDs are strings. Decimal nutrition/weight/measurement values are decimal **strings**; use decimal arithmetic rather than binary floating point. Null food macros remain null in individual records and count as zero in totals. - Stored/individual nutrition and totals are not rounded to whole numbers by the API. Whole-number scoreboard formatting is a client display concern. - `calories` is the effective saved value, including manual overrides. `calculated_calories` is protein×4 + carbs×4 + fat×9, rounded once. Their difference must not be used to erase a manual choice. - Targets are integer grams with their derived integer calories. No medical estimate is generated by reading them. - All six meal positions have stable names/order even on days with no saved meal rows. Journal foods include `meal_position`. - JSON errors use `{"error":{"code":"...","message":"..."}}`. Clients should branch on code/status, not copy text. Additive changes may occur within v1; clients should tolerate unknown fields. Breaking contract changes need a new version. ## Security and errors | Status | Code | Meaning | | --- | --- | --- | | 400 | `invalid_parameter` | Invalid date, pagination, query, or barcode format. | | 401 | `unauthorized` | Missing/unknown/malformed/expired/revoked token; all are deliberately indistinguishable. Includes `WWW-Authenticate: Bearer`. | | 402 | `membership_required` | The existing billing policy is enforced for this account and access has expired. This implementation does not enable billing or enroll users. | | 403 | `insufficient_scope` | Credential lacks the implemented read scope. | | 404 | `not_found` | Unknown endpoint, missing record, or another owner's record. | | 429 | `rate_limited` | Shared API limit of 120/minute/IP, or additional barcode limit of 30/minute/IP. Includes `Retry-After: 60`; retry with backoff. | | 404 | `product_not_found` | Barcode absent from Open Food Facts; manual entry remains available. | | 422 | `incomplete_nutrition` | Product lacks usable macros; enter the label manually. | | 503 | `food_database_unavailable` | Temporary upstream failure. Includes `Retry-After: 60`; retry with backoff. | All private journal/body data lookups are owner-scoped; food previews use only the shared public-source services and never search another account’s journal; legacy unassigned entries are not adopted or exposed. Native/non-browser clients do not encounter the web modern-browser gate. Token-management creation/revocation stays behind normal browser login and CSRF protection, with password confirmation and an issuance throttle. API controllers do not authenticate through cookies. ## Deliberately not implemented yet - Native password login, session renewal/refresh, or a full OAuth flow. - Food/weight/measurement/target writes and their idempotency/validation contracts. - Photo metadata, upload, comparison, or private image download. - Billing endpoints, StoreKit/Google verification, account export/deletion APIs. - A client SDK or live API execution console. These remain work on PN-5 and its related cards. Do not mark the entire feature or its broad requirements complete based on this slice. ## Verification ```sh mise x ruby@3.3.4 -- bin/rails test test/models/api_token_test.rb test/integration/api_tokens_test.rb test/integration/api_v1_test.rb test/integration/api_food_lookup_test.rb test/integration/api_contract_test.rb test/integration/api_documentation_test.rb ``` Tests cover expiry/revocation, secret storage/display, password confirmation, token limits, CSRF, ownership and legacy records, strict inputs, precision/units, timezone boundaries, membership enforcement, structured throttling, and response-contract alignment. Browser checks use Chromium/WebKit emulation and are not evidence of physical-device testing.