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:
- Use the right key. A key limited to allowed referrers refuses requests from an app.
- Keep a visitor token. Make one
userToken, keep it across launches and send it with every request. - Read the answer stream.
/answerstreams server-sent events. - Send events, with retries. Send clicks and conversions
with the search’s
queryId, and queue them while the device is offline.
Choose a key
Section titled “Choose a key”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.
Keep a visitor token
Section titled “Keep a visitor token”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 }()}object Visitor { fun token(context: Context): String { val prefs = context.getSharedPreferences("shoof", Context.MODE_PRIVATE) prefs.getString("userToken", null)?.let { return it } val t = "anon-" + UUID.randomUUID().toString() prefs.edit().putString("userToken", t).apply() return t }}// shared_preferences and uuid from pub.devFuture<String> visitorToken() async { final prefs = await SharedPreferences.getInstance(); final saved = prefs.getString('shoof.userToken'); if (saved != null) return saved; final t = 'anon-${const Uuid().v4()}'; await prefs.setString('shoof.userToken', t); return t;}// @react-native-async-storage/async-storageimport AsyncStorage from "@react-native-async-storage/async-storage";import { randomToken } from "@shoof/js-client";
export async function visitorToken(): Promise<string> { const saved = await AsyncStorage.getItem("shoof.userToken"); if (saved) return saved; const t = randomToken(); await AsyncStorage.setItem("shoof.userToken", t); 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.
Search
Section titled “Search”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)}// OkHttp and kotlinx.serialization@Serializable data class Hit(val id: String, val title: String, val url: String? = null, val image: String? = null)@Serializable data class SearchResponse(val hits: List<Hit>, val nbHits: Int, val queryId: String? = null)
private val json = Json { ignoreUnknownKeys = true }private val http = OkHttpClient()
suspend fun search(q: String, userToken: String): SearchResponse = withContext(Dispatchers.IO) { val body = buildJsonObject { put("q", q); put("lang", "en"); put("hitsPerPage", 20); put("userToken", userToken) }.toString().toRequestBody("application/json".toMediaType()) val req = Request.Builder() .url("https://api.shoofai.com/v1/apps/my-store/search") .header("x-shoof-api-key", "shf_pub_…") .post(body) .build() http.newCall(req).execute().use { res -> check(res.isSuccessful) { "search failed: ${res.code}" } json.decodeFromString(res.body!!.string()) }}// http from pub.devFuture<Map<String, dynamic>> search(String q, String userToken) async { final res = await http.post( Uri.parse('https://api.shoofai.com/v1/apps/my-store/search'), headers: {'x-shoof-api-key': 'shf_pub_…', 'content-type': 'application/json'}, body: jsonEncode({'q': q, 'lang': 'en', 'hitsPerPage': 20, 'userToken': userToken}), ); if (res.statusCode != 200) throw Exception('search failed: ${res.statusCode}'); return jsonDecode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;}import { ShoofClient } from "@shoof/js-client";
const client = new ShoofClient({ appId: "my-store", apiKey: "shf_pub_…", userToken: await visitorToken(),});
const res = await client.search({ q: "running shoes", lang: "en", hitsPerPage: 20 });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.
Stream AI answers
Section titled “Stream AI answers”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 } } }}// com.squareup.okhttp3:okhttp-ssefun answer(q: String, userToken: String, onText: (String) -> Unit): EventSource { val body = buildJsonObject { put("q", q); put("userToken", userToken) } .toString().toRequestBody("application/json".toMediaType()) val req = Request.Builder() .url("https://api.shoofai.com/v1/apps/my-store/answer") .header("x-shoof-api-key", "shf_pub_…") .post(body) .build() return EventSources.createFactory(http).newEventSource(req, object : EventSourceListener() { override fun onEvent(source: EventSource, id: String?, type: String?, data: String) { when (type) { "delta" -> onText(Json.parseToJsonElement(data).jsonObject["text"]!!.jsonPrimitive.content) "done", "error" -> source.cancel() // "sources": show the citations } } })}Stream<String> answer(String q, String userToken) async* { final req = http.Request('POST', Uri.parse('https://api.shoofai.com/v1/apps/my-store/answer')) ..headers.addAll({'x-shoof-api-key': 'shf_pub_…', 'content-type': 'application/json'}) ..body = jsonEncode({'q': q, 'userToken': userToken}); final res = await http.Client().send(req); var event = 'message'; await for (final line in res.stream.transform(utf8.decoder).transform(const LineSplitter())) { if (line.startsWith('event:')) { event = line.substring(6).trim(); } else if (line.startsWith('data:') && event == 'delta') { yield (jsonDecode(line.substring(5)) as Map<String, dynamic>)['text'] as String; } else if (event == 'done' || event == 'error') { return; } }}// Expo SDK 52+: expo/fetch streams response bodies; React Native's own fetch doesn't.import { fetch as expoFetch } from "expo/fetch";
const client = new ShoofClient({ appId: "my-store", apiKey: "shf_pub_…", userToken: await visitorToken(), fetch: expoFetch as unknown as typeof fetch,});
await client.answer({ q: "is it waterproof?" }, { onSources: (sources) => setSources(sources), onDelta: (text) => setAnswer((a) => a + text),});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.
Send events
Section titled “Send events”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 (
scenePhasebecomes.background,onStop, theAppLifecycleState.pausedstate,AppStatechanges tobackground); - give each batch an
Idempotency-Keyheader, 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.
Generate a client
Section titled “Generate a client”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:
openapi-generator generate -i https://docs.shoofai.com/openapi.yaml -g swift5 -o ShoofClientopenapi-generator generate -i https://docs.shoofai.com/openapi.yaml -g kotlin -o shoof-clientopenapi-generator generate -i https://docs.shoofai.com/openapi.yaml -g dart-dio -o shoof_clientThe 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.
Checklist
Section titled “Checklist”- A search key with no referrers, or secured keys from your server. Never the admin key.
- One
userTokenper install, kept across launches. - The
queryIdfrom 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
429and402instead of an empty screen. - Try it first on the public demo app, with no account.