Is my POST method correct

//Is my post method correct because google and claude are telling me I must use content type for the json and use .setvalue. I thought that my process was correct because I encode the data to turn into json and then make the request

func createTask(_ task: Task) async throws -> Task { if let url = URL(string: "(baseURL)/todos"){

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        let encoder = JSONEncoder()
        do{
            let data = try encoder.encode(task)
            request.httpBody = data
            let (data, response) = try await URLSession.shared.data(for: request)
            return task
            //we want to make encoder and then turn the data into json and put it in body
            
        }
        catch{
            throw JSONErrors.encodingFailed
        }
        
    }
    else{
        throw URLError(.badURL)
    }
    
    
}
Answered by Claude31 in 854030022

@kevdoescode you ask if the post is correct. That probably means it does not work properly.

If so, do you get and error message ? Is the result different from what you expected ?

To use the forum properly, you have to provide this information, not just ask someone to correct your code.

I advise also to read the very good post on how to properly use the forum: https://developer.apple.com/forums/thread/706527

A simple code sample here: https://forums.swift.org/t/sending-an-http-post-request-to-an-api-using-swift/62457

This line: func createTask(_ task: Task) async throws -> Task { if let url = URL(string: "(baseURL)/todos"){

isn't in the formatted code block. Please, when you make a post, please check that your formatting is correct. If it isn't, just edit it and correct it.

Anyway:

func createTask(_ task: Task) async throws -> Task { if let url = URL(string: "(baseURL)/todos"){

is wrong. You need a \ before (baseURL)

Why are you relying on some AI trash app to figure out such a simple bit of coding? Spend a few minutes and learn how to write a POST request using actual sources of information. This Claude thing isn't going to replace actual knowledge. The very fact that you've had to ask us humans kinda proves that.

Accepted Answer

@kevdoescode you ask if the post is correct. That probably means it does not work properly.

If so, do you get and error message ? Is the result different from what you expected ?

To use the forum properly, you have to provide this information, not just ask someone to correct your code.

I advise also to read the very good post on how to properly use the forum: https://developer.apple.com/forums/thread/706527

A simple code sample here: https://forums.swift.org/t/sending-an-http-post-request-to-an-api-using-swift/62457

Is my POST method correct
 
 
Q