Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

Create a generic GET and POST Request struct in Swift

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-sonnet-20241022’s answer.
  1. User

    Create a generic GET and POST Request struct in Swift

  2. Assistant

    Certainly! Below is a simple example of generic GET and POST request structs in Swift using Codable for request and response types. This approach uses generics to handle any type of request body and response body.

    import Foundation
    
    // Generic GET Request
    struct GetRequest<Response: Decodable> {
        let url: URL
        
        func execute(completion: @escaping (Result<Response, Error>) -> Void) {
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            
            URLSession.shared.dataTask(with: request) { data, response, error in
                if let error = error {
                    completion(.failure(error))
                    return
                }
                
                guard let data = data else {
                    completion(.failure(NSError(domain: "No data", code: -1, userInfo: nil)))
                    return
                }
                
                do {
                    let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
                    completion(.success(decodedResponse))
                } catch {
                    completion(.failure(error))
                }
            }.resume()
        }
    }
    
    // Generic POST Request
    struct PostRequest<Request: Encodable, Response: Decodable> {
        let url: URL
        let body: Request
        
        func execute(completion: @escaping (Result<Response, Error>) -> Void) {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            
            do {
                request.httpBody = try JSONEncoder().encode(body)
            } catch {
                completion(.failure(error))
                return
            }
            
            URLSession.shared.dataTask(with: request) { data, response, error in
                if let error = error {
                    completion(.failure(error))
                    return
                }
                
                guard let data = data else {
                    completion(.failure(NSError(domain: "No data", code: -1, userInfo: nil)))
                    return
                }
                
                do {
                    let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
                    completion(.success(decodedResponse))
                } catch {
                    completion(.failure(error))
                }
            }.resume()
        }
    }
    

    Usage Example

    // Define your response model
    struct User: Codable {
        let id: Int
        let name: String
    }
    
    // GET example
    let getRequest = GetRequest<User>(url: URL(string: "https://api.example.com/user/1")!)
    getRequest.execute { result in
        switch result {
        case .success(let user):
            print("User: \(user)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
    
    // POST example
    struct CreateUserRequest: Codable {
        let name: String
    }
    
    let postRequest = PostRequest<CreateUserRequest, User>(
        url: URL(string: "https://api.example.com/user")!,
        body: CreateUserRequest(name: "John Doe")
    )
    
    postRequest.execute { result in
        switch result {
        case .success(let user):
            print("Created User: \(user)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
    

    This setup provides a reusable and type-safe way to perform GET and POST requests with any Codable request and response types. Let me know if you want me to add support for headers, query parameters, or other HTTP methods!

  3. User

    expand the struct to allow for PUT and DELETE

  4. Assistant

    Certainly! Here's an expanded version of the generic request struct that supports GET, POST, PUT, and DELETE HTTP methods. To keep things clean and reusable, I'll create a single generic APIRequest struct that handles all four methods, with optional request bodies for methods that support them.


    Generic APIRequest Struct Supporting GET, POST, PUT, DELETE

    import Foundation
    
    enum HTTPMethod: String {
        case GET, POST, PUT, DELETE
    }
    
    struct APIRequest<Request: Encodable, Response: Decodable> {
        let url: URL
        let method: HTTPMethod
        let body: Request?
    
        init(url: URL, method: HTTPMethod, body: Request? = nil) {
            self.url = url
            self.method = method
            self.body = body
        }
    
        func execute(completion: @escaping (Result<Response, Error>) -> Void) {
            var request = URLRequest(url: url)
            request.httpMethod = method.rawValue
    
            // Set JSON content type for methods with a body
            if method == .POST || method == .PUT {
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            }
    
            // Encode body if present
            if let body = body, (method == .POST || method == .PUT) {
                do {
                    request.httpBody = try JSONEncoder().encode(body)
                } catch {
                    completion(.failure(error))
                    return
                }
            }
    
            URLSession.shared.dataTask(with: request) { data, response, error in
                if let error = error {
                    completion(.failure(error))
                    return
                }
    
                guard let data = data else {
                    completion(.failure(NSError(domain: "No data", code: -1, userInfo: nil)))
                    return
                }
    
                do {
                    let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
                    completion(.success(decodedResponse))
                } catch {
                    completion(.failure(error))
                }
            }.resume()
        }
    }
    

    Usage Examples

    // Example response model
    struct User: Codable {
        let id: Int
        let name: String
    }
    
    // GET request (no body)
    let getRequest = APIRequest<EmptyRequest, User>(url: URL(string: "https://api.example.com/user/1")!, method: .GET)
    getRequest.execute { result in
        switch result {
        case .success(let user):
            print("User: \(user)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
    
    // POST request (with body)
    struct CreateUserRequest: Codable {
        let name: String
    }
    
    let postRequest = APIRequest<CreateUserRequest, User>(
        url: URL(string: "https://api.example.com/user")!,
        method: .POST,
        body: CreateUserRequest(name: "John Doe")
    )
    
    postRequest.execute { result in
        switch result {
        case .success(let user):
            print("Created User: \(user)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
    
    // PUT request (with body)
    struct UpdateUserRequest: Codable {
        let name: String
    }
    
    let putRequest = APIRequest<UpdateUserRequest, User>(
        url: URL(string: "https://api.example.com/user/1")!,
        method: .PUT,
        body: UpdateUserRequest(name: "Jane Doe")
    )
    
    putRequest.execute { result in
        switch result {
        case .success(let user):
            print("Updated User: \(user)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
    
    // DELETE request (no body)
    let deleteRequest = APIRequest<EmptyRequest, User>(
        url: URL(string: "https://api.example.com/user/1")!,
        method: .DELETE
    )
    
    deleteRequest.execute { result in
        switch result {
        case .success(let user):
            print("Deleted User: \(user)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
    
    // Helper empty request struct for requests without a body
    struct EmptyRequest: Codable {}
    

    Explanation

    • HTTPMethod enum defines the supported HTTP methods.
    • APIRequest struct is generic over Request and Response types.
    • The body is optional and only encoded for POST and PUT requests.
    • For GET and DELETE, the body is ignored (and typically not sent).
    • EmptyRequest is a helper struct to use when no request body is needed (e.g., GET, DELETE).

    If you want, I can also help you add support for headers, query parameters, or async/await style!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.