Code samples
Small, complete clients you can copy into a project. Each one keeps the token, sends it as a bearer token, reads the data / error envelope, and books with a client_uuid.
You can also generate a full client from /api/booking/v1/openapi.json with OpenAPI Generator (kotlin, swift5, dart-dio, typescript-fetch).
Kotlin (Android, OkHttp)
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.util.UUID
class BookingApiException(val status: Int, val code: String, message: String) : Exception(message)
class BookingApi(private val baseUrl: String, private val tokenStore: TokenStore) {
private val http = OkHttpClient()
private val json = "application/json".toMediaType()
// Call from a background thread or wrap in withContext(Dispatchers.IO)
private fun call(method: String, path: String, body: JSONObject? = null): Any {
val builder = Request.Builder().url(baseUrl + path)
.method(method, body?.toString()?.toRequestBody(json))
tokenStore.token?.let { builder.header("Authorization", "Bearer $it") }
http.newCall(builder.build()).execute().use { response ->
val payload = JSONObject(response.body!!.string())
if (!response.isSuccessful) {
val error = payload.getJSONObject("error")
if (response.code == 401 && error.getString("code") == "unauthorized") tokenStore.token = null
throw BookingApiException(response.code, error.getString("code"), error.getString("message"))
}
return payload.get("data")
}
}
fun requestCode(identifier: String) =
call("POST", "/auth/code", JSONObject().put("identifier", identifier)) as JSONObject
fun verifyCode(identifier: String, code: String, name: String? = null): JSONObject {
val body = JSONObject().put("identifier", identifier).put("code", code)
.put("device", "${android.os.Build.MODEL} (Android)")
if (name != null) body.put("name", name)
val data = call("POST", "/auth/verify", body) as JSONObject
tokenStore.token = data.getString("token") // keep it in EncryptedSharedPreferences / Keystore
return data.getJSONObject("customer")
}
fun availability(typeId: Int, date: String, duration: Int) =
call("GET", "/availability?facility_type_id=$typeId&date=$date&duration=$duration") as JSONObject
/** Create the requestKey once when the player taps Book, and pass the same key on retries. */
fun book(typeId: Int, start: String, duration: Int, courtId: Int?, requestKey: String = UUID.randomUUID().toString()): JSONObject {
val body = JSONObject().put("facility_type_id", typeId).put("start", start)
.put("duration", duration).put("client_uuid", requestKey)
if (courtId != null) body.put("court_id", courtId)
return call("POST", "/bookings", body) as JSONObject
}
fun booking(id: Int) = call("GET", "/bookings/$id") as JSONObject
}
interface TokenStore { var token: String? }
Open the payment page in a Custom Tab (androidx.browser:browser):
val booking = api.book(1, "2026-11-22 21:00", 90, courtId = 1)
val payment = booking.getJSONObject("payment")
if (payment.getBoolean("required_online")) {
CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(payment.getString("pay_url")))
}
// in onResume(): api.booking(id) until state == "confirmed" (see Online payment)
Swift (iPhone, URLSession)
import Foundation
struct BookingAPIError: Error, LocalizedError {
let status: Int, code: String, message: String
var errorDescription: String? { message }
}
final class BookingAPI {
let baseURL: URL
var token: String? // keep it in the Keychain
init(baseURL: URL) { self.baseURL = baseURL }
private func call(_ method: String, _ path: String, body: [String: Any]? = nil) async throws -> Any {
var request = URLRequest(url: URL(string: baseURL.absoluteString + path)!)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
if let body { request.httpBody = try JSONSerialization.data(withJSONObject: body) }
let (data, response) = try await URLSession.shared.data(for: request)
let status = (response as! HTTPURLResponse).statusCode
let payload = try JSONSerialization.jsonObject(with: data) as! [String: Any]
if let error = payload["error"] as? [String: String] {
if status == 401 && error["code"] == "unauthorized" { token = nil }
throw BookingAPIError(status: status, code: error["code"] ?? "", message: error["message"] ?? "")
}
return payload["data"]!
}
func requestCode(_ identifier: String) async throws -> [String: Any] {
try await call("POST", "/auth/code", body: ["identifier": identifier]) as! [String: Any]
}
func verifyCode(_ identifier: String, code: String, name: String? = nil) async throws -> [String: Any] {
var body: [String: Any] = ["identifier": identifier, "code": code, "device": "iPhone"]
if let name { body["name"] = name }
let data = try await call("POST", "/auth/verify", body: body) as! [String: Any]
token = data["token"] as? String
return data["customer"] as! [String: Any]
}
func availability(typeId: Int, date: String, duration: Int) async throws -> [String: Any] {
try await call("GET", "/availability?facility_type_id=\(typeId)&date=\(date)&duration=\(duration)") as! [String: Any]
}
/// Create requestKey once when the player taps Book; reuse it on retries.
func book(typeId: Int, start: String, duration: Int, courtId: Int?, requestKey: String) async throws -> [String: Any] {
var body: [String: Any] = ["facility_type_id": typeId, "start": start,
"duration": duration, "client_uuid": requestKey]
if let courtId { body["court_id"] = courtId }
return try await call("POST", "/bookings", body: body) as! [String: Any]
}
}
Open the payment page:
import SafariServices
if let payment = booking["payment"] as? [String: Any],
payment["required_online"] as? Bool == true,
let url = URL(string: payment["pay_url"] as! String) {
present(SFSafariViewController(url: url), animated: true)
}
// in safariViewControllerDidFinish: GET /bookings/{id} until state == "confirmed"
Flutter (Dart, package:http)
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:uuid/uuid.dart';
class BookingApiException implements Exception {
final int status; final String code; final String message;
BookingApiException(this.status, this.code, this.message);
@override String toString() => message;
}
class BookingApi {
final String baseUrl;
String? token; // keep it in flutter_secure_storage
BookingApi(this.baseUrl);
Future<dynamic> _call(String method, String path, [Map<String, dynamic>? body]) async {
final request = http.Request(method, Uri.parse('$baseUrl$path'))
..headers['Content-Type'] = 'application/json';
if (token != null) request.headers['Authorization'] = 'Bearer $token';
if (body != null) request.body = jsonEncode(body);
final response = await http.Response.fromStream(await request.send());
final payload = jsonDecode(utf8.decode(response.bodyBytes));
if (payload['error'] != null) {
if (response.statusCode == 401 && payload['error']['code'] == 'unauthorized') token = null;
throw BookingApiException(response.statusCode, payload['error']['code'], payload['error']['message']);
}
return payload['data'];
}
Future<Map> requestCode(String identifier) async => await _call('POST', '/auth/code', {'identifier': identifier});
Future<Map> verifyCode(String identifier, String code, {String? name}) async {
final data = await _call('POST', '/auth/verify',
{'identifier': identifier, 'code': code, if (name != null) 'name': name, 'device': 'Flutter app'});
token = data['token'];
return data['customer'];
}
Future<Map> availability(int typeId, String date, int duration) async =>
await _call('GET', '/availability?facility_type_id=$typeId&date=$date&duration=$duration');
/// Create requestKey once with const Uuid().v4() when the player taps Book; reuse it on retries.
Future<Map> book(int typeId, String start, int duration, {int? courtId, required String requestKey}) async =>
await _call('POST', '/bookings', {
'facility_type_id': typeId, 'start': start, 'duration': duration,
if (courtId != null) 'court_id': courtId, 'client_uuid': requestKey,
});
}
Open pay_url with url_launcher in LaunchMode.inAppBrowserView, then poll GET /bookings/{id} when the app resumes.
TypeScript (web or React Native)
export class BookingApiError extends Error {
constructor(public status: number, public code: string, message: string) { super(message); }
}
export class BookingApi {
token: string | null = null;
constructor(private baseUrl: string) {}
private async call<T>(method: string, path: string, body?: object): Promise<T> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (this.token) headers.Authorization = `Bearer ${this.token}`;
const response = await fetch(this.baseUrl + path, {
method, headers, body: body ? JSON.stringify(body) : undefined,
});
const payload = await response.json();
if (payload.error) {
if (response.status === 401 && payload.error.code === "unauthorized") this.token = null;
throw new BookingApiError(response.status, payload.error.code, payload.error.message);
}
return payload.data as T;
}
requestCode(identifier: string) { return this.call("POST", "/auth/code", { identifier }); }
async verifyCode(identifier: string, code: string, name?: string) {
const data = await this.call<{ token: string; customer: object }>(
"POST", "/auth/verify", { identifier, code, name, device: "Web" });
this.token = data.token;
return data.customer;
}
availability(typeId: number, date: string, duration: number) {
return this.call("GET", `/availability?facility_type_id=${typeId}&date=${date}&duration=${duration}`);
}
/** requestKey = crypto.randomUUID() when the player taps Book; reuse it on retries. */
book(typeId: number, start: string, duration: number, requestKey: string, courtId?: number) {
return this.call("POST", "/bookings", {
facility_type_id: typeId, start, duration, court_id: courtId, client_uuid: requestKey,
});
}
}
A web app on another domain needs its origin in Settings > Court Booking > Player apps (API); see Errors and limits.
Was this page helpful?