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:

  1. Define your struct and conform it to Codable:

    struct Drink: Codable {
        let name: String
        let size: String
        let price: Double
    }
    
  2. 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)")
    }
    
  3. 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.