ChatGPT API in Swift: Integration in 30 Minutes

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Swift and ChatGPT Are Love at First Commit



Imagine: you're writing an app in Swift, and suddenly you realize it lacks "brains." The user asks a question, and your code is silent as a fish. Sound familiar? Until recently, adding intelligence to an iOS app was difficult: you either had to write your own NLP model or integrate heavy libraries. Now it's different.



ChatGPT API in Swift is not just a trendy feature, but a real tool that can turn your app into a smart assistant. Want to build an AI assistant, content generator, or just a chatbot? All of this can be implemented in one evening. In this article, I'll show you how to connect OpenAI API in Swift from scratch, without unnecessary magic or complex architectures. Let's go!



What Do We Need?



Before jumping into the code, let's figure out the tools. To work with ChatGPT in iOS, you only need three things:



  • OpenAI API key — register at platform.openai.com, create a key in the API Keys section. Guard it like the apple of your eye — don't commit it to Git!
  • Xcode 15+ — to use modern Swift with async/await.
  • Basic understanding of SwiftUI or UIKit — I'll show an example in SwiftUI, but the networking logic is universal.


Ready? Then open Xcode, create a new project (iOS App, SwiftUI, language — Swift) and let's start writing code.



Request Architecture: How to "Talk" to ChatGPT in Swift



OpenAI provides a REST API. This means we will send HTTP requests and receive JSON responses. All communication goes through the endpoint https://api.openai.com/v1/chat/completions. We need to send a POST request with a body containing an array of messages (role + content) and get a response from the model.



Let's create a data model for the request and response. This is a perfect example of using Decodable in Swift.



// Model for a single messagestruct Message: Codable {    let role: String      // "system", "user" or "assistant"    let content: String}

// Request structure for the APIstruct ChatGPTRequest: Codable { let model: String let messages: [Message] let temperature: Double?

init(model: String = "gpt-4o-mini", messages: [Message], temperature: Double = 0.7) { self.model = model self.messages = messages self.temperature = temperature }}

// Response structurestruct ChatGPTResponse: Codable { struct Choice: Codable { let message: Message let finishReason: String?

enum CodingKeys: String, CodingKey { case message case finishReason = "finish_reason" } }

let choices: [Choice]}


Note the CodingKeys — in Swift, property names are typically written in camelCase, while the API returns snake_case. This is a standard technique for working with API in Swift.



Network Layer: URLSession + async/await



Now for the most interesting part — sending the request. I'll use modern async/await to keep the code clean and readable. No closures or delegates — just beauty.



class ChatGPTService {

private let apiKey: String private let session = URLSession.shared private let baseURL = URL(string: "https://api.openai.com/v1/chat/completions")!

init(apiKey: String) { self.apiKey = apiKey }

func sendMessage(_ text: String) async throws -> String {

// Form messages: system prompt + user request let systemMessage = Message(role: "system", content: "You are a helpful assistant. Answer briefly and to the point.") let userMessage = Mess

Blogs

Book Recommendations