# Hostwise Developer Documentation — documentation-v1 (llms-full) # Complete plain-text documentation for AI-assisted integration with Hostwise (https://hostwise.fr). # Hostwise is the availability source of truth for short-term rentals: your booking website reads the # catalogue and live availability from Hostwise, books through Hostwise, and is notified when anything changes. ## THE MODEL - Account: one Hostwise customer (a property manager). All data is isolated per account. - Brand: one booking website belonging to an account. An account can run several brands. Each brand holds its own API keys and webhook subscriptions and sees ONLY the listings published to it. - Listing: a bookable unit (an apartment, or a room type with several identical units). Identified by a stable string listingId. - Calendar: the single availability answer, per listing and per date. Every booking, from your site or from any other sales channel the property is sold on, lands in the same calendar; there is exactly one truth to read. ## THE THREE RULES EVERY INTEGRATION FOLLOWS 1. Events are notifications, not data. A webhook names WHAT changed, never the new values. On receipt, re-fetch the named listings/dates through the API. Deliveries can be delayed, retried, or out of order; a fetch at processing time is always current. 2. Keep a periodic poll as the floor (hourly is typical). Push accelerates; the poll catches anything dropped. Never remove it. 3. Check availability live at the moment of payment via the Gateway API and FAIL CLOSED: any error or timeout during checkout means "treat as unavailable". Cached calendars are for browsing only. ## CONVENTIONS - Base URL https://hostwise.fr, HTTPS only, JSON bodies. - Dates are ISO 8601 YYYY-MM-DD. A stay occupies checkin..checkout-1; the checkout day is free for the next arrival (back-to-back stays share that date). - Availability status is one of: available | booked | blocked. For selling, booked and blocked are identical (not sellable). ## AUTHENTICATION OAuth 2.1 client credentials grant (conforms to draft-ietf-oauth-v2-1). Your brand holds one credential (client_id + client_secret); it authenticates ONLY at the token endpoint. Every API call carries the short-lived Bearer token it mints: POST /api/oauth/token Content-Type: application/x-www-form-urlencoded body: grant_type=client_credentials&client_id=...&client_secret=... -> 200 { access_token: "alpy_at_...", token_type: "Bearer", expires_in: 3600, scope: "storefront gateway ingest" } (Cache-Control: no-store) Then on every API call: Authorization: Bearer alpy_at_... - Resource requests accept Bearer ONLY. Basic on an API route -> 401 with a WWW-Authenticate: Bearer challenge. The raw secret never travels on resource calls. - CACHE the token; reuse until expiry or a 401 invalid_token, then mint ONCE and retry. Never mint per request (the token endpoint is rate-limited). - At the token endpoint: credentials in the BODY (required method) or HTTP Basic; never both in one request; never in the URL. Tokens are opaque — do not parse. - scope param optional: omitted = all the key's scopes; a space-separated subset mints a narrower token. Errors: invalid_client / invalid_request / invalid_scope / unsupported_grant_type (JSON, per spec). No refresh tokens — just authenticate again. - 401 + WWW-Authenticate: Bearer error="invalid_token" on a resource call = token expired -> mint a fresh token, retry once. A failed MINT (bad secret) never heals by retrying. Token client (copy as-is; framework-free, Node 18+ — the same client Hostwise's own brand integrations run in production; mint-once, cache, renew 5 min early, one re-mint on 401): export function alpyTokenSource({ base = 'https://hostwise.fr', clientId, clientSecret }) { let cached = null, inflight = null; const url = base.replace(/\/+$/, '') + '/api/oauth/token'; async function mint() { const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }) }); const data = await res.json().catch(() => null); if (!res.ok || !data?.access_token) throw new Error(`token mint ${res.status}: ${data?.error || ''}`); cached = { value: data.access_token, expiresAt: Date.now() + (data.expires_in - 300) * 1000 }; return cached.value; } return { async get(force = false) { if (force) cached = null; if (cached && Date.now() < cached.expiresAt) return cached.value; if (!inflight) inflight = mint().finally(() => { inflight = null; }); return inflight; } }; } export async function alpyFetch(tokens, url, init = {}) { const attempt = async (force) => fetch(url, { ...init, headers: { ...(init.headers || {}), authorization: `Bearer ${await tokens.get(force)}` } }); let res = await attempt(false); if (res.status === 401) res = await attempt(true); return res; } - HTTPS-ONLY, and plaintext API calls are REFUSED (403), never redirected: base64 is encoding, not encryption — TLS protects the credential — and an http:// call would leak the header in cleartext before any response arrives, so it fails loudly instead of silently working via a redirect. Base URL must be https://hostwise.fr. - The credential identifies your brand; Hostwise resolves account + published listings from it. You never send an account id and can never see another brand's data. - Scopes (least privilege): storefront (read), gateway (live availability + book/cancel/modify), ingest (push your own bookings). Missing scope -> 403. Bearer tokens carry the scopes they were minted with (frozen at mint). - Gateway paths carry your brand slug (/api/gateway/:brand/...) which must equal the credential's brand, else 403 brand mismatch. - Server-to-server only. Never ship the key OR a token to a browser or app binary. - Rate limits ~600 req/min per route; 429 -> back off. ## STOREFRONT API (read side; scope: storefront) GET /api/storefront/listings -> { brand, listings: [ { id, name, title, description, propertyType, address, city, destination, lat, lng, bedrooms, bathrooms, accommodates, beds, areaSquareMeters, rooms: [ { kind, kindLabel, title, beds: [ { type, qty, label } ], bedsText } ], currency, basePrice, photos: [url...], thumbnail, content: { summary, space, access, interactionWithGuests, neighborhood, transit, notes }, checkInTime, checkOutTime, minNights, maxNights, amenities: { unit: [titles...], building: [titles...] }, customFields: { "": , ... }, position } ] } Fields: - name: short display name (falls back to title). title/description: the long title and the full description as one text; description = the parts of content joined in order. - title / description / content may be brand-specific: a listing can carry a custom description assigned to your brand, and you receive that one; otherwise the primary. Same keys either way. - content: the description as separate parts (summary, space, access, interactionWithGuests, neighborhood, transit, notes) so a page can lay out its own sections. Every key always present; an unwritten part is null. - bedrooms, bathrooms (may be fractional, 1.5), accommodates: headline counts; any may be null. - beds: total sleeping places (a bunk bed counts as two). null when unknown, never 0. - rooms: the room arrangement in the manager's order. Each room: kind (stable key — bedroom, living_room, full_bathroom, half_bathroom, kitchen, balcony, office, ...), kindLabel (display), title (display), beds: [ { type (stable — single, bunk, double, queen, king, sofa), qty, label } ], bedsText (ready-to-print, e.g. "2 single beds · 1 sofa bed", or null for a room with no beds). Always an array; empty when the listing has not been arranged. Render as sleeping arrangements; ITERATE it and treat unknown kind/type values as display-only — new ones can appear. - destination: where the listing sells (the manager's destination name, plain text) or null; place an unseen listing in your own destination grid with it. - basePrice: base nightly rate in `currency`, major units (210, not cents) or null - the "from" price (every price the storefront and gateway return carries the brand's markup set on Hostwise's Markups page, or the listing's own override for that brand; 0 by default) for a card before dates; quote with the per-date rates from the availability endpoint. - areaSquareMeters: floor area in m², rounded; null when unknown, never 0 (convert to sq ft yourself). - checkInTime, checkOutTime: local HH:MM or null. - minNights, maxNights: the listing's default stay limits or null; per-date minimums from the availability endpoint take precedence for a given stay. - position: the manager's display order on this brand (0-based); list endpoint only. Photos are permanent CDN URLs, ordered, first = cover. Serve directly; do not copy. amenities are display-ready titles from Hostwise's amenity catalogue, alphabetical, grouped unit (the apartment) / building (shared facilities); both arrays always present, may be empty — render as-is, no mapping needed. customFields are extras the manager wanted to tell guests beyond the standard fields: keys are the manager's own labels, values string|number|boolean, object always present, may be empty. NOT a fixed schema — ITERATE the object, never read a hardcoded key, because fields can be added/renamed/removed by the manager at any time. Every field with a value is sent; an absent key just means it was not filled in. HTML-escape labels AND values: both are operator-entered text. GET /api/storefront/listings/:id -> one listing (404 unless published to YOUR brand). GET /api/storefront/listings/:id/availability?from=YYYY-MM-DD&to=YYYY-MM-DD (range <= 400 days) -> { id, availability: [ { date, status, price, minNights } ] } POST /api/storefront/quote body { from, to, guests } -> { from, to, nights, guests, results: [ { id, title, total, currency, perNight } ] } Displaying photos: URLs are CDN links that accept sizing parameters in the URL — request the size with this helper (copy it; framework-free, browser or Node). URLs without the sizing segment pass through untouched. Always HTML-escape URLs. export function imageVariant(url, { w, h, q = 'auto', f = 'auto' } = {}) { if (typeof url !== 'string' || !url.includes('/image/upload/')) return url; const t = [w && `w_${w}`, h && `h_${h}`, q && `q_${q}`, f && `f_${f}`].filter(Boolean).join(','); return t ? url.replace('/image/upload/', `/image/upload/${t}/`) : url; } // Best-resolution rendering: offer several widths and let the BROWSER choose by slot size and // screen density (a 480px slot on a 3x phone wants 1440 real pixels). Use with : // export function imageSrcset(url, widths = [480, 960, 1440, 2560]) { return widths.map((w) => `${imageVariant(url, { w })} ${w}w`).join(', '); } Best resolution = imageSrcset + sizes on (browser picks width by slot x screen density — sharp on Retina/phones without desktop bytes on mobile). Fixed sizes for small slots: {w:480}. q_auto = per-image compression; f_auto = WebP/AVIF when the browser accepts. Guidance: keep a copy of catalogue+availability in your own cache; refresh hourly AND on webhook receipt; never take money against the cache. GET /api/storefront/partners -> { brand, partners: [ { kind, label, partner, connected_system, markup_pct (the account's markup on this partner, or null), items: [ { id, name, description, unit, unit_label, pricing: "fixed"|"live", price_cents (marked up when markup_pct is set), partner_price_cents (then), currency, price_label } ], quotes: { endpoint: "/api/gateway/:brand/partner-quotes", method: "POST", body: { kind } } | null } ], how_to_book } WHAT THE ACCOUNT CAN SELL ALONGSIDE A STAY: the services (menus + prices) of the partners the account connected on Hostwise. Hostwise publishes it, your site sells it; nothing to keep up to date by hand - the next read has every change. A "live" item has no price here: quote it at checkout (gateway partner-quotes), then book with the quote_id. ## GATEWAY API (live + booking; scope: gateway; all paths /api/gateway/:brand/...) GET /api/gateway/:brand/availability?listingId=X&from=&to= (or listingIds=a,b,c for bulk) -> { listingId, currency, days: [ { date, status, price, minNights } ] } price carries the brand's markup (Markups page in Hostwise; 0 by default) Bulk form -> { listings: [ ... ] }. No range cap. FAIL CLOSED on 5xx inside checkout. POST /api/gateway/:brand/reservations body { idempotencyKey (required, unique per booking attempt — REUSE on retry), listingId (required), checkin (required), checkout (required), guests, guest { firstName, lastName, email, phone }, money { accommodation, currency }, reference (your confirmation code) } -> { alpyReservationId, status: "confirmed", idempotentReplay: false } Atomic: checks the nights, takes them in Hostwise's calendar, closes them on every other sales channel the property is sold on, and emits availability.changed + reservation.changed to every entitled brand — closing the dates on the account's other storefronts in seconds. Errors: - 409 code DATES_UNAVAILABLE: some night not sellable. Refresh calendar; do not retry. - 400 invalid input; 404 unknown/inactive/unpublished listing. - 5xx/timeout: outcome unknown -> retry with the SAME idempotencyKey. A prior success returns the same reservation with idempotentReplay: true. Never mint a new key for a retry. POST /api/gateway/:brand/reservations/:reference/cancel :reference = the reference you supplied at create. Frees the nights everywhere the property is sold, notifies brands. Idempotent: second cancel -> { status: "cancelled", alreadyCancelled: true }. Cancellation is terminal. POST /api/gateway/:brand/reservations/:reference/modify body { checkin, checkout }. Atomic date change: new nights checked+taken and freed ones released together, or nothing changes. 409 DATES_UNAVAILABLE if the new range is not fully sellable. POST /api/gateway/:brand/partner-quotes body { kind, start_date, end_date, adults, children, destination, currency, details } -> 200 { quote: { quote_id, total_cents, currency, expires_at, partner } } the connected partner's live price 404 no_connected_partner (sell from your own list or not at all); 409 unavailable (detail); 502 partner_error -> show "not available right now", never a guessed price. Book it through the Ingest API with the quote_id. Checkout pattern: (1) live availability check at payment; (2) take payment your side; (3) create with a stored idempotency key, retry same key on network failure; (4) on DATES_UNAVAILABLE after payment (rare race) refund per your policy — Hostwise took nothing. ## INGEST API (push side; scope: ingest) POST /api/ingest — record a booking your site created and settled itself, so it appears in the account's back office (reservations, multi-calendar, cleaning, reporting). body { brand, confirmation_code (YOUR stable reference — the idempotency key; re-push to update), listing_id, check_in, check_out, guests, guest { name, email, phone }, money { total, currency }, status, payment { method: "split"|"single", paid, of, label, complete }, addons: [ { type, external_id, guest_name, start_date, end_date, amount_cents, currency, details, items: [ { id, qty } ], // the partner's menu items sold (from /api/storefront/partners) quote_id } ] // a live item: the quote booked at checkout } Partner services: type = the partner's kind (transfer | rental | pass). Hostwise prices the partner's side from its menu (items) or the quote, opens the request to the partner, and the partner confirms in its portal or from its own system. Idempotent on confirmation_code: re-pushing updates in place (payment progress, extras, cancellation). Ingest RECORDS; it does not reserve. If the stay occupies a listing Hostwise distributes, book it through the Gateway API instead so the dates are atomically blocked everywhere. ## WEBHOOKS (Hostwise -> your site) Registration: your brand registers endpoint URL(s); each gets a signing secret; several secrets may be valid at once (rotation without a flag day). Delivery: POST headers: alpy-id: evt_... unique per event, STABLE across retries — dedup on this alpy-timestamp: reject if outside +/- 5 minutes (replay protection) alpy-signature: v1, space-separated list during rotation body: { id, type, version: 1, occurred_at, brand, sequence, data: { listing_ids: [..], from?, to?, reason?, reservation_id?, status?, external_id?, check_in?, check_out? } } Signature: HMAC-SHA256 over `${id}.${timestamp}.${rawBody}` with your secret, base64. Verify against the RAW body bytes BEFORE JSON parsing; accept if ANY offered v1 value matches; timing-safe compare. Event types: - availability.changed: the calendar moved for listing_ids - availability, nightly price or minimum stay (reason 'rates' = a price / min-stay change). from/to bound the change; absent = whole calendar may have moved. Handler: re-fetch availability for each id (named range, else full window) - the feed carries price and minNights per night, so one re-fetch refreshes all three. - reservation.changed: created/changed/cancelled. external_id is your own reference where Hostwise knows it (null for bookings that did not originate from your site). Handler: update local status, then refresh EVERY id in listing_ids (a relocation frees one listing and books another). - listing.changed: content changed. Handler: re-fetch the listing, upsert. - listing.removed: withdrawn from your brand. Handler: deactivate locally; never delete. - ping.test: connectivity. Return 200. Unknown types MUST return 200 and be ignored (Hostwise adds types over time). Semantics: - Ordering not guaranteed (hence notification-not-data). - Retries on non-2xx/timeout: fast at first (~30s), then exponential to hourly. 2xx = ack, 5xx = transient. Event id identical across retries — dedup on it; make handlers idempotent; mark processed only after work succeeded so a crash reprocesses instead of dropping. - Coalescing: bursts fold into one event with the union of listings and the widest from/to. Widening is safe — you refresh a few extra days. - sequence is gap-free per brand: a gap means you missed an event — call the catch-up endpoint. - The poll stays. Push accelerates; your scheduled refresh is the floor. Catch-up ("what did I miss?" — gateway scope, brand key auth, no signature): GET /api/gateway/:brand/events?since_sequence=N&limit=500 (or ?since=) -> { brand, latest_sequence, count, has_more, events: [ ...webhook envelopes... ] } Process each event exactly as a webhook delivery (same handler, same dedup on id — a caught-up event may also have been delivered). Page on has_more from the last received sequence. Retention 30 days. The stream exists from the brand's first day, before any webhook endpoint is registered — integrations can start pull-only and add push later. Feed status ("is this feed alive?"): GET /api/gateway/:brand/events/status -> { brand, sequence, last_event_at, last_delivered_at, pending, endpoints: [ { active, last_success_at, last_failure_at, consecutive_failures } ] } Alert if pending grows or consecutive_failures climbs (your receiver failing, Hostwise backing off); compare sequence with the last processed to detect gaps proactively. Receiver checklist: raw-body capture; 400 missing headers/stale timestamp; 401 bad signature; dedup on alpy-id with processed-after-success; handle known types; 200 unknown; 5xx when your upstream fetch fails so Hostwise retries. ## MONITORING GET /health (public, unauthenticated) -> {"status":"ok","db":"ok","version":"..."}. Point uptime monitors here. Non-200 or db not ok: serve guest pages from your cache and fail closed at checkout. ## INTEGRATION CHECKLIST (a new brand site, end to end) 1. Obtain brand API keys (scopes: storefront, gateway, and ingest if you push bookings). 2. Pull catalogue + availability into your cache (Storefront API); schedule an hourly refresh. Read /api/storefront/partners too: the partner services the account sells alongside a stay (menus, prices); sell those, quote live items at checkout (gateway partner-quotes), push the add-on with items / quote_id. 3. Stand up the webhook receiver (checklist above); register the endpoint + secret. 4. Wire checkout to the Gateway API with idempotency keys and fail-closed availability. 5. Optionally push self-settled bookings via Ingest, idempotent on your confirmation code. 6. Go live; keep the poll; monitor for sequence gaps. # End of documentation-v1.