Skip to content

Mobile apps

A mobile app talks to the same REST API as the widget: plain JSON over HTTPS, plus one server-sent event stream for AI answers. There is no native SDK to install. A few dozen lines of URLSession, OkHttp or http cover search, and you can also generate a typed client from the OpenAPI spec.

A mobile app has to handle four things itself that the JavaScript client handles in a browser:

  1. Use the right key. A key limited to allowed referrers refuses requests from an app.
  2. Keep a visitor token. Make one userToken, keep it across launches and send it with every request.
  3. Read the answer stream. /answer streams server-sent events.
  4. Send events, with retries. Send clicks and conversions with the search’s queryId, and queue them while the device is offline.

Apps search with a search key (shf_pub_…). It can only read, so it’s safe to ship inside an app. Never ship an admin key.

Allowed referrers work from what a browser says in the Origin or Referer header. An app sends neither header, so a key with referrers refuses every request from it with 403 forbidden. In the dashboard, create a separate search key for the app (named “iOS app”, say) and leave its referrers empty. Rate limits count each device by its IP address, as they count each browser.

Your server can also make a secured key for each signed-in user and pass it to the app:

  • the user only sees what their key’s filters allow, such as their price list or their own documents;
  • the key expires, so a key copied out of the app stops working;
  • you can revoke the app’s keys without shipping an update.

A user who isn’t signed in can still use the app’s plain search key.

Personalized results, recently viewed items, trending items and click-learned ranking all depend on knowing which searches and events come from the same visitor. Make a random token the first time the app runs, keep it, and send it as userToken on every search, answer and event:

enum Visitor {
static let token: String = {
let key = "shoof.userToken"
if let t = UserDefaults.standard.string(forKey: key) { return t }
let t = "anon-" + UUID().uuidString.lowercased()
UserDefaults.standard.set(t, forKey: key)
return t
}()
}

Use a random token, not the device’s advertising ID. When a user signs in, you can switch to a token derived from their account (a hash of their user id, not their email), so their history follows them across devices.

POST /v1/apps/{appId}/search takes the search request as JSON, with the key in the x-shoof-api-key header. Keep the response’s queryId for the events the search leads to.

struct SearchResponse: Decodable {
struct Hit: Decodable { let id: String; let title: String; let url: String?; let image: String? }
let hits: [Hit]
let nbHits: Int
let queryId: String?
}
func search(_ q: String) async throws -> SearchResponse {
var req = URLRequest(url: URL(string: "https://api.shoofai.com/v1/apps/my-store/search")!)
req.httpMethod = "POST"
req.setValue("shf_pub_…", forHTTPHeaderField: "x-shoof-api-key")
req.setValue("application/json", forHTTPHeaderField: "content-type")
req.httpBody = try JSONSerialization.data(withJSONObject: [
"q": q, "lang": "en", "hitsPerPage": 20, "userToken": Visitor.token,
])
let (data, res) = try await URLSession.shared.data(for: req)
guard (res as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) }
return try JSONDecoder().decode(SearchResponse.self, from: data)
}

For search as you type, call GET /autocomplete on each keystroke and cancel the request before it (a Task you cancel, an OkHttp Call, an AbortController). Searches from the same visitor typing on within a minute count once.

Errors are JSON, {"error": {"code": "...", "message": "..."}}. Show your own message for 429 rate_limited and 402 quota_exceeded, rather than an empty results screen. Every error code.

POST /v1/apps/{appId}/answer returns text/event-stream: a sources event with the records and the queryId, many delta events with the next piece of text, then done. An error event can replace the rest of the stream. What each event holds.

// iOS 15+: URLSession.bytes reads the stream as it arrives.
func answer(_ q: String, onText: @escaping (String) -> Void) async throws {
var req = URLRequest(url: URL(string: "https://api.shoofai.com/v1/apps/my-store/answer")!)
req.httpMethod = "POST"
req.setValue("shf_pub_…", forHTTPHeaderField: "x-shoof-api-key")
req.setValue("application/json", forHTTPHeaderField: "content-type")
req.httpBody = try JSONSerialization.data(withJSONObject: ["q": q, "userToken": Visitor.token])
let (bytes, _) = try await URLSession.shared.bytes(for: req)
var event = "message"
for try await line in bytes.lines {
if line.hasPrefix("event:") {
event = line.dropFirst(6).trimmingCharacters(in: .whitespaces)
} else if line.hasPrefix("data:") {
let data = Data(line.dropFirst(5).utf8)
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
switch event {
case "delta": onText(obj?["text"] as? String ?? "")
case "error": throw NSError(domain: "shoof", code: 1)
default: break // "sources": show the citations; "done": stop the spinner
}
}
}
}

Render the answer as Markdown. Citations come as [1], [2], matching the n of each source in the sources event. Link each one to the source’s url, or to the screen that shows that record in your app.

Events feed analytics, trending, bought together and click-learned ranking. Send them to POST /v1/apps/{appId}/events, up to 100 at a time:

When Event
The user opens a result {"type": "click", "queryId": "…", "objectId": "sku-1", "position": 3}
A product or article screen opens {"type": "view", "objectId": "sku-1"}
The user adds to cart {"type": "add_to_cart", "objectId": "sku-1", "queryId": "…"}
The order is placed, one per item {"type": "conversion", "objectId": "sku-1", "queryId": "…", "value": 140, "currency": "AED", "orderId": "10521"}

Add userToken to every event, and timestamp (epoch milliseconds) when the event happened. position starts at 1 and counts across pages: the third result on page two of 20 is 23. Keep the queryId with the item through to the cart, so a purchase is credited to the search that found it.

Phones go offline and apps get suspended, so don’t send events one at a time:

  • keep them in a queue saved on the device, with the time each one happened;
  • send the queue every 30 seconds or so, and when the app goes to the background (scenePhase becomes .background, onStop, the AppLifecycleState.paused state, AppState changes to background);
  • give each batch an Idempotency-Key header, a UUID made with the batch, and send the same batch with the same key until it’s accepted (202), so a retry after a lost response isn’t counted twice;
  • drop events more than a few days old.

The API is described by an OpenAPI 3.1 spec, at docs.shoofai.com/openapi.yaml and shoofai.com/openapi.json. OpenAPI Generator turns it into a typed client:

Terminal window
openapi-generator generate -i https://docs.shoofai.com/openapi.yaml -g swift5 -o ShoofClient
openapi-generator generate -i https://docs.shoofai.com/openapi.yaml -g kotlin -o shoof-client
openapi-generator generate -i https://docs.shoofai.com/openapi.yaml -g dart-dio -o shoof_client

The generated client covers search, autocomplete, recommendations and events. For /answer, use the streaming code above: generators read a text/event-stream response as one string.

  • A search key with no referrers, or secured keys from your server. Never the admin key.
  • One userToken per install, kept across launches.
  • The queryId from each search on its click, add-to-cart and conversion events.
  • Events queued on the device, sent in batches with an Idempotency-Key.
  • Answers streamed and their citations linked.
  • Messages for 429 and 402 instead of an empty screen.
  • Try it first on the public demo app, with no account.