OpenAI from Swift / iOS

SDK examples · All languages and providers · API reference

OpenAI does not publish an official Swift SDK, and URLSession is all you need. A community SDK works too if it lets you set the host or base path and sends the token as Authorization: Bearer. Your OpenAI key stays on the server; the app holds only a token that expires in one hour.

1. Set up the service

In the dashboard, create an app, add a service and store your OpenAI key in it:

openai  →  https://api.openai.com/v1

2. Get a token for the user

The app asks MyAppToken for a token with its app ID and your identifier for the user. The token lasts one hour; rate limits and analytics are tied to that user.

let api = "https://api.myapptoken.com/api/v1"
let appId = "<app-id>"

struct Session: Decodable { let access_token: String; let expires_in: Int }

func sessionToken(userId: String) async throws -> String {
    var req = URLRequest(url: URL(string: "\(api)/auth/simple")!)
    req.httpMethod = "POST"
    req.setValue("application/json", forHTTPHeaderField: "Content-Type")
    req.httpBody = try JSONSerialization.data(
        withJSONObject: ["app_id": appId, "user_id": userId])
    let (data, _) = try await URLSession.shared.data(for: req)
    return try JSONDecoder().decode(Session.self, from: data).access_token
}

Renew it before it expires with POST /auth/refresh (send the current, still-valid token as Authorization: Bearer); if that fails, request a new one. With Firebase App Check enabled, also send the App Check header on proxy calls.

3. Call OpenAI

let proxy = URL(string: "https://api.myapptoken.com/api/v1/proxy/<app-id>/openai")!

func chat(_ text: String, jwt: String) async throws -> Data {
    var req = URLRequest(url: proxy.appendingPathComponent("chat/completions"))
    req.httpMethod = "POST"
    req.setValue("Bearer \(jwt)", forHTTPHeaderField: "Authorization")
    req.setValue("application/json", forHTTPHeaderField: "Content-Type")
    req.httpBody = try JSONSerialization.data(withJSONObject: [
        "model": "gpt-4o-mini",
        "messages": [["role": "user", "content": text]],
    ])
    let (data, _) = try await URLSession.shared.data(for: req)
    return data
}

let jwt = try await sessionToken(userId: "user-123")
let reply = try await chat("Hello", jwt: jwt)
// Before: https://api.openai.com/v1/chat/completions with the sk-… key

What changed

Direct to the providerThrough MyAppToken
Base URLhttps://api.openai.com/v1https://api.myapptoken.com/api/v1/proxy/<app-id>/openai
Credentialprovider key (sk-…)the user's token from /auth/simple

More: OpenAI guide · rate limits · async jobs.

Start free — no credit card; the Free plan covers 10,000 requests a month.