How can I serialize a struct to send to an api
Asked on 2024-07-30
1 search
To serialize a struct in Swift to send to an API, you can use the Codable protocol, which is a type alias for the Encodable and Decodable protocols. This allows you to easily convert your struct to and from JSON. Here’s a basic example:
-
Define your struct and conform it to
Codable:struct Drink: Codable { let name: String let size: String let price: Double } -
Serialize the struct to JSON:
let drink = Drink(name: "Latte", size: "Medium", price: 3.50) let encoder = JSONEncoder() do { let jsonData = try encoder.encode(drink) // Convert jsonData to a JSON string for sending to an API if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) } } catch { print("Failed to encode drink: \(error)") } -
Send the JSON data to an API:
let url = URL(string: "https://api.example.com/drinks")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error sending data: \(error)") return } // Handle response here } task.resume()
For more detailed information on working with Swift and APIs, you might find the session Explore the Swift on Server ecosystem useful, especially the part where it discusses handling JSON and database interactions.

Migrate your app to Swift 6
Experience Swift 6 migration in action as we update an existing sample app. Learn how to migrate incrementally, module by module, and how the compiler helps you identify code that’s at risk of data races. Discover different techniques for ensuring clear isolation boundaries and eliminating concurrent access to shared mutable state.

A Swift Tour: Explore Swift’s features and design
Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.

Explore the Swift on Server ecosystem
Swift is a great language for writing your server applications, and powers critical services across Apple’s cloud products. We’ll explore tooling, delve into the Swift server package ecosystem, and demonstrate how to interact with databases and add observability to applications.
