API reference
The public website API currently exposes two same-origin endpoints: contact and chat. The full product API is provisioned privately for each workspace.
Back to docsPrivate beta
Access is provisioned by the team. No public package is promised before it exists.
POST /api/contact
Accepts JSON or form data. Validates name/email, checks a honeypot, rate-limits by IP, and writes to D1 when configured.
Form submissions return 303 to /contact/?sent=1; JSON submissions return 201 {success:true}.
curl -X POST https://loopnow.in/api/contact \
-H 'content-type: application/json' \
-d '{"name":"Asha","email":"asha@example.com","intent":"audit","consent":true}' POST /api/chat
Accepts { messages: [{ role, content }] } and streams Server-Sent Events from the Qwen-backed assistant. Maximum 12 requests per minute per IP.
Errors return JSON with a 4xx/5xx status. The chat widget consumes the SSE stream directly.
curl -N -X POST https://loopnow.in/api/chat \
-H 'content-type: application/json' \
-d '{"messages":[{"role":"user","content":"What does Growth cost?"}]}' Rate limits
Contact: 5 requests per IP per 60 seconds. Chat: 12 messages per IP per 60 seconds. Both are enforced in D1; production adds Cloudflare WAF rules.
Errors
400 invalid body, 405 wrong method, 429 rate limited, 503 not configured, 504 model timeout. Error responses are JSON and never include stack traces.
Product API
The workspace API (contacts, campaigns, automations, transactional, analytics) is provisioned privately with scoped keys. Request access through the contact form; we do not publish a dead endpoint or a package that does not exist.
The short version
- Two routes exist: POST /api/chat, which streams Server-Sent Events, and POST /api/contact, which writes to D1.
- Chat reads messages[] plus an optional page string and keeps only the last twenty messages.
- Authentication is a server-side binding, not a client key; there is no Authorization header to send.
- Rate limits are twelve chat requests and five contact submissions per IP per minute, enforced in D1.
- Errors are JSON objects with one error string; 429 responses carry no Retry-After header.
- Contact is not idempotent, so a retried form post can create a duplicate enquiry.
The surface is two routes, and that is the whole list
This reference documents every publicly callable route on loopnow.in. There are two. POST /api/chat streams an answer from the site assistant, and POST /api/contact records an enquiry. Both are declared as on-demand rendered endpoints in the Astro project, which means they execute in the Cloudflare Worker rather than being prerendered into static files at build time. Every other path under /api that you might expect from a platform of this scope does not exist yet, and this page will not describe it as though it does.
The routes share a host, a deployment and a database binding, but almost nothing else. Chat is read-heavy and talks to a model gateway over the network; contact is write-heavy and talks to D1. Chat streams a body that the client must parse incrementally; contact returns a tiny JSON object or a redirect. Chat tolerates a browser that disappears mid-response because there is nothing to clean up; contact must finish its insert before it answers, because a confirmation on screen is a claim that the row exists.
Both handlers respond to a GET with 405 and a JSON error, and the contact handler includes an Allow header naming POST. Neither sets CORS headers, so a browser on another origin cannot read a response even though a server-side caller could reach the URL. That is not an oversight to work around: these are first-party routes for the site’s own interface, and the private workspace API is the supported route for third-party integrations.
- POST /api/chat — JSON in, text/event-stream out
- POST /api/contact — JSON or form in, JSON or 303 out
- GET on either — 405, JSON body, Allow on contact
- No CORS headers are emitted, so browser callers stay same-origin
- No Authorization header is read anywhere
Anatomy of a chat request body
The body is a JSON object with two recognised keys. messages is an array of objects, each with a role and a content string. page is an optional string describing where the reader is. Any other key is ignored rather than rejected, which keeps older clients working when the front end adds a field. There is no model selector, no temperature control, no tools array and no system prompt override; those values are fixed in the handler so that a caller cannot spend more of the metered budget than the route intends.
Validation is permissive about roles and strict about size. The handler keeps the last twenty entries and drops anything earlier, so a long conversation degrades gracefully instead of failing. Each remaining entry must be an object with a string content of at most four thousand characters; anything else produces 400 with the message Message too long. A role of assistant is preserved, and every other role value is treated as user, so a stray system role cannot smuggle instructions into the prompt at a higher privilege than a normal turn.
Two ordering details are worth remembering because they surprise people testing the failure paths. The credential check happens before the body is parsed, so an unconfigured deployment returns 503 even for malformed JSON. And the empty-messages check happens after parsing but before rate limiting, so an empty array costs you nothing from the counter. If you are writing a client, send well-formed bodies, keep them short, and treat 503 as a configuration signal rather than a validation error.
- messages — array, last 20 kept
- messages[].role — assistant preserved, all else user
- messages[].content — string, 4000 char ceiling
- page — optional string, 200 char ceiling
- page — must start with a slash to be used
Authentication: secrets on the server, nothing in the client
There is no bearer token, no signature and no cookie involved in either route. The browser that loads loopnow.in can call chat because it is already on the origin, and the handler does not attempt to identify it beyond an address for rate limiting. This is a deliberate design for a marketing site assistant: a key that ships in a bundle is not a secret, and a key that must be pasted by a reader is a conversion barrier. The consequence is that the route is limited rather than authenticated.
The credential that does exist is a Worker secret named QWEN_API_KEY, read at request time from the cloudflare:workers environment alongside QWEN_BASE_URL and QWEN_MODEL. The handler composes a server-to-server request with an Authorization header derived from that secret, calls the gateway’s completions path, and returns the response body downstream. The secret is never written to a response, never logged with its value, and never included in an error string. If the gateway sits behind Cloudflare Access, an optional service token pair is attached as Access headers instead of putting the origin on the public internet.
For contact, the only secret-shaped value is IP_HASH_SALT, used to digest addresses before they touch the database. If the binding is missing the code falls back to a literal default, which keeps local development working but is a poor choice in production: an unsalted hash of a small IPv4 range is reversible by enumeration. Treat the salt as part of the deployment checklist, on the same level as the database binding itself.
The stream format, frame by frame
A successful chat response is a text/event-stream body with three headers that matter: the content type including charset, cache-control set to no-store, and x-accel-buffering set to no so an intermediate proxy does not hold the first tokens back. There is no content-length, because the length is unknown when the headers are written. The handler passes the upstream body through rather than re-encoding it, so the frame shape is the gateway’s OpenAI-compatible shape rather than something invented here.
Each event is a line beginning with data: followed by a JSON object, then a blank line. The incremental text lives at choices[0].delta.content. A final frame is commonly the literal string [DONE], which carries no JSON and therefore must be skipped rather than parsed. Anything that is not a data line, including comments and blank separators, should be ignored by a tolerant reader. The site’s own widget splits the buffer on double newlines, iterates lines, strips the prefix, skips [DONE], parses, and appends the delta.
Two practical rules follow. Buffer by event boundary, not by chunk, because a network read can split a JSON object in half and a naive parser will throw. And do not assume one delta per word: the model may emit several characters, a whole phrase or nothing at all in a frame, so accumulate text rather than replacing it. If the connection closes without any content, the widget shows a fallback message pointing at the contact form instead of leaving an empty bubble on screen.
- content-type — text/event-stream; charset=utf-8
- cache-control — no-store
- x-accel-buffering — no
- frame — data: {choices:[{delta:{content}}]}
- terminator — data: [DONE], not JSON
Grounding: how a page hint becomes context
The page field is a hint, not a filter. It is truncated to two hundred characters, stripped of its query string, and stripped of trailing slashes; a value that does not begin with a slash is discarded entirely. A reader on /pricing/ therefore sends /pricing, and the handler looks for a knowledge row whose URL matches /pricing/. If nothing matches, it falls back to the first path segment, so a product page can borrow from its family. If that also returns nothing, the search runs across the whole index.
The query itself is built from the newest user message only, not the whole conversation. The text is lowercased, punctuation and symbols become spaces, words of three characters or fewer are dropped, and the first eight surviving terms are joined with OR. That is a recall-oriented query: it prefers finding something relevant over being precise. Results are ordered by the index’s relevance function and capped at six passages, each trimmed to nine hundred characters before being pasted into the system prompt with a numbered title and URL.
Retrieval is best-effort in the strongest sense. The whole block sits inside a try that swallows failures, including a missing table or a query the index rejects, and the request continues with the static facts prompt. The model is told to cite a URL when it uses a passage, but citations are not verified afterwards; treat any link in an answer as something to check rather than a guarantee. This is why the assistant refuses questions outside the site’s scope instead of guessing.
Rate limiting in D1, window by window
Both routes use the same table and the same technique. The current Unix time is floored to a sixty-second boundary, and a row keyed by bucket and window is upserted with an increment that returns the new count. If the count exceeds the ceiling the request is refused. A single statement does the read and the write, so two concurrent requests cannot both observe a stale count and slip through. The bucket is scoped by route and by caller, which keeps chat and contact from consuming each other’s allowance.
Chat keys the bucket on the client address, falling back to a connecting-IP header and finally to the literal string unknown. That last fallback is worth knowing: if address information is unavailable, every such caller shares one bucket, and the thirteenth request of the minute blocks the rest. Contact keys on a salted SHA-256 digest of the same address instead of the address itself, because the digest is stored on the submission row and a raw address would be personal data sitting in a table that does not need it.
The limiter only runs when the database binding is present. On a deployment without D1, chat still works and simply is not limited, while contact cannot store anything and returns 503 for a valid submission. Neither route emits a Retry-After header, and neither reports remaining budget in a response header. If you need to schedule traffic, assume the window boundary is a wall-clock minute and leave headroom rather than trying to land exactly on the allowance.
- bucket — chat:ip or contact:hash
- window_start — Unix time minus remainder of 60
- chat ceiling — 12 per window
- contact ceiling — 5 per window
- response on exceed — 429, JSON error only
Status codes and an honest retry table
Chat can return 400, 429, 502, 503 or 504. The 400 family covers a body that is not JSON, a missing messages array, and a message over the character ceiling; each comes with a short human sentence rather than a field path. The 503 means the model credential is absent, which is a deployment problem. The 504 means the fetch to the gateway threw or exceeded its forty-five second timeout. The 502 means the gateway answered with a non-success status or with no body at all.
Contact can return 400, 429, 503, 201 or 303. The 400 cases are invalid, invalid-name and invalid-email, where invalid means the body could not be parsed at all. The 503 means the database binding is absent or the insert threw, and the handler logs the database error without returning it. A JSON caller gets 201 with a success boolean; a form caller gets 303 to /contact/?sent=1, or to the same page with an error flag and a short code, which is how the confirmation renders without JavaScript.
Retry guidance follows from that split. A 400 is terminal: the same bytes will fail identically. A 429 is terminal for the current minute but safe to repeat after the boundary, and repeating it immediately makes things worse because each attempt increments the counter. A 503 needs a configuration change, not patience. A 502 or 504 is the only class where a single retry with a short backoff is reasonable. Because no route returns Retry-After, do not wait for that header.
Contact: JSON callers versus form callers
The contact handler chooses its response shape from the request, not from a query parameter. It treats a content type containing application/x-www-form-urlencoded or multipart/form-data as a form, and anything else as JSON. It treats a request as wanting JSON when the Accept header contains application/json, even if the body was a form. That combination lets a browser form post receive a redirect while a script posting the same fields receives a machine-readable body, without two endpoints or a version flag.
A successful JSON call returns 201 with a success flag and nothing else: no row identifier, no echo of the submitted data, no confirmation email is dispatched by this code. A successful form call returns 303 with a Location header pointing at the contact page with a sent flag. Failures mirror the same split: a form caller is redirected with an error code in the query string, and a JSON caller gets a status and a body. The redirect codes are deliberately short tokens rather than prose, because they end up in a URL.
One caveat about the Accept header: a form post that also asks for JSON will receive a 201 and will not navigate. That is correct behaviour but confusing if you wired a progressive-enhancement script to intercept the submit and forgot to remove the header. The reverse is also true. A fetch call that omits Accept gets the redirect path, and fetch will follow the 303 and hand you the contact page HTML rather than a JSON object.
Validation rules, the honeypot and the consent record
The honeypot is checked first, before any validation and before the database is touched. Two field names count: company_url, which the site’s own form renders off-screen, and website, which exists for other clients. A non-empty value returns the success shape immediately, so a bot sees 201 or a redirect and no row is written. Because the check precedes validation, an empty name with a filled honeypot also returns success. That asymmetry is intentional and is the cheapest part of the anti-abuse design.
For real submissions, the name must be at least two characters and at most one hundred, and the email must match a simple pattern and stay under two hundred. The message is trimmed and truncated at five thousand characters, company at one hundred and twenty, phone at thirty, and the intent at fifty with general as the default. There is no phone validation and no disposable-domain check, so a well-formed but useless enquiry can still be stored; the model of abuse here is automation, not a determined human.
Consent is recorded as two columns rather than a boolean. When the submitted value is on or true, the handler writes a version string and a timestamp; otherwise both stay null. The version is a literal in the source, which makes it a record of which notice text applied at submission time rather than a user-supplied field. The row also carries the path the form was submitted from, which is how the team can tell whether an enquiry came from the contact page, the assistant panel or a campaign landing page.
- name — trimmed, 2 to 100
- email — pattern checked, max 200
- company — max 120, optional
- phone — max 30, optional
- intent — max 50, defaults to general
- consent — on or true writes version and time
- source_path — stored as sent, may be null
Idempotency, duplicates and the cost of a blind retry
Chat is stateless and therefore idempotent in the only sense that matters here: repeating a request produces a new answer and stores nothing. Contact is not. There is no idempotency key in the body, no uniqueness constraint on the email column, and no deduplication window. Two identical submissions produce two rows, and both look equally real to whoever reads the inbox. This is a deliberate simplification for a low-volume form, and it is the behaviour you should design around rather than assume away.
The practical failure mode is a request that succeeds on the server but fails in transit. The insert commits, the response is lost, and the caller sees a network error. Retrying creates a duplicate. The mitigation available today is procedural: the form flow redirects to a confirmation URL, so a human refresh does not resubmit, and an automated caller should treat a timeout as an unknown outcome, check with the recipient before repeating, or include a client-side marker in the message text so duplicates are recognisable.
Nothing in the response tells you whether a submission was a duplicate, and the handler does not return the inserted identifier. If you need exactly-once semantics for enquiries, that belongs in the private workspace API and in your own system of record, not in a marketing form handler. Saying so is less satisfying than advertising an idempotency header, but a header that is ignored is worse than no header at all.
Local reproduction with curl and a dev vars file
Every behaviour on this page can be exercised locally. Create a .dev.vars file with the gateway base URL, a key and a model identifier, apply the migrations to the local D1 database, seed the knowledge table if you want retrieval to do anything, then run the dev server. Without the key, chat answers 503 and you can verify the degraded path in a single request. With it, the same curl command streams tokens to your terminal, which is the fastest way to see whether a client-side parsing bug is yours or the server’s.
For contact, the interesting cases are the ones that do not write. Post a body with the honeypot filled and confirm you get a success response with no new row. Post one with a one-character name and confirm a 400 naming the field. Post six times inside a minute and watch the sixth return 429. Then check the database directly: the intent column, the consent pair and the hashed address are the three places where a mistaken assumption about the code shows up quickly.
One environment quirk deserves a line of its own. The Worker runtime cannot reach a private tailnet address, so a gateway that lives on one must be exposed through a localhost proxy during development. Production solves the same problem with a Cloudflare Tunnel and, optionally, an Access service token. If a local chat request times out at forty-five seconds while the same call succeeds from a shell, the proxy is the first thing to inspect, not the model.
- QWEN_BASE_URL — gateway base, no trailing slash needed
- QWEN_API_KEY — required, absence means 503
- QWEN_MODEL — defaults to qwen36
- IP_HASH_SALT — set it locally too
- npm run db:migrate:local — before the first insert
- curl -N — do not buffer the stream
What is planned, and what will not be published early
The workspace API, signed webhooks, software development kits and the SMTP relay are all designed or partially built, and none of them is a public contract today. The webhook catalogue needs a final signature scheme and replay window before event names mean anything. The SDK pages need a published package before an install command is honest. The SMTP page needs a host that accepts connections before it prints one. Each of those is a prerequisite, not a marketing decision.
There is one visible seam worth naming. The database schema includes a chat_leads table, and the chat route does not write to it. The table exists because a lead-capture flow from the assistant panel is planned, but the current route only handles rate limiting and retrieval. If you are reading the schema and inferring a feature, that inference is reasonable and currently wrong. The route’s behaviour, not the migration, is the source of truth.
When these surfaces ship they will appear here with the same shape as the two live routes: request body, response, limits, errors and a local reproduction path. Until then, the correct way to plan around them is to ask during onboarding and to treat the answer as a schedule, not a specification. A page that admits this is more useful than one that fills the gap with plausible-looking JSON.
Frequently asked questions
What exactly does the chat endpoint accept?
A JSON object with messages and an optional page. messages is an array of objects carrying a role and a content string; the last twenty entries are kept and each content string must be at most four thousand characters. page must be a string starting with a slash and is truncated at two hundred characters. Unknown keys are ignored. There is no field for model, temperature or system prompt.
Why is there no Retry-After header on a 429?
Because the handler does not set one. The limit is a fixed one-minute wall-clock bucket, so the wait is bounded by the next minute boundary, but that is knowledge you have to bring. Treat a 429 as meaning stop until the boundary rather than as a suggestion to retry immediately. Every attempt inside the window increments the counter and extends the practical block.
How long can a chat response take before it fails?
The upstream fetch is wrapped in a forty-five second timeout. If the gateway has not produced a response by then the fetch aborts and the route returns 504 with a JSON error. Once the stream has started, the timeout no longer applies to individual tokens because the body is passed through, so a stream can in principle run longer than forty-five seconds after the first byte.
Does the chat route store conversations?
No. Messages are validated, trimmed, used to build the prompt and discarded when the request ends. The database is used for the rate-limit counter and to read the knowledge index. A chat_leads table exists in the schema, but the chat handler does not insert into it, so a conversation never becomes a stored record through this route.
What is the difference between 502 and 504 on chat?
A 504 means the fetch to the gateway threw or hit the forty-five second timeout, so no usable response arrived. A 502 means the gateway did answer, but with a non-success status or without a body. Both are logged server-side with a truncated detail string, and neither returns the upstream message to the caller. One retry is reasonable for either; a second failure usually indicates a real incident.
Can I send a phone number to the contact endpoint?
Yes. The handler reads a phone field, trims it and truncates it at thirty characters, and stores it. The site’s own contact form does not render a phone input, so the column is usually null for browser submissions. There is no format validation on it, which means a value that is not dialable will still be stored if it fits the length bound.
What does the consent field actually write?
When the value is the string on or true, the handler writes a consent version literal and the current timestamp in milliseconds. Any other value leaves both columns null. The version is not supplied by the caller, so it records which notice text was live at submission time. Sending the boolean true in JSON works because the comparison is against the strings on and true.
Why do I get HTML back instead of JSON from a fetch call?
Your request did not ask for JSON. The handler only returns a JSON body when the Accept header contains application/json; otherwise a form submission is answered with a 303 redirect, and fetch follows redirects by default and resolves with the contact page HTML. Add an explicit Accept header and the same call returns a 201 with a small success object.
Is the 45 second timeout configurable per request?
No. It is a constant in the handler and there is no request field that changes it, alongside the fixed temperature, token ceiling and thinking flag. The intent is that a caller cannot extend the window and hold a Worker invocation open indefinitely. If your use case needs longer generation, the website assistant is the wrong surface and the private workspace API is the right conversation.
What happens if two requests arrive in the same second?
The rate-limit increment is a single upsert with a returning clause, so both requests see a consistent count rather than racing on separate reads. One of them receives the higher number and may be refused at the boundary. The same statement pattern is used for contact, keyed by the hashed address, so the two routes cannot consume each other’s budget even under bursty traffic.