iosjsonswiftrest

Swift Post Request - JSON Body is empty


I am trying to do a POST Request based on a REST server API.

Everytime I execute the code the server doesn't receive the sent body. The server receives a body looking like this: {}

The struct used in the request looks as follows:

struct CreateUser: Codable {
   let first_name: String
   let email: String
   let password: String
}

The Request is done as follows:

let userToRegister = CreateUser(firstName: "Max", email: "max.mustermann@gmail.com", password: "SECRET_PASSWORD")
let str = API_ENDPOINT
var request : URLRequest = URLRequest(url: URL(string: str)!)
let encoder = JSONEncoder()
let jsonData = try? encoder.encode(userToRegister)
request.httpBody = jsonData
request.httpMethod = "POST"
return URLSession.shared.dataTask(with: request, completionHandler: {(data,response,error) in
    DispatchQueue.main.async {
        if let httpResponse = response as? HTTPURLResponse {
            if httpResponse.statusCode == 200 {
                //Code for successful request
            } else {
                //Code for failure in request
            }
        }
    }
})

Solution

  • I have solved the problem. You have to add the following lines:

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")