Trying to get AI generated text from deepai.com
the example they provided looks like this:
curl \
-F 'text=YOUR_TEXT_HERE' \
-H 'api-key:quickstart-QUdJIGlzIGNvbWluZy4uLi4K' \
https://api.deepai.org/api/text-generator
and I'm trying to reproduce the same in swift:
var request = URLRequest(url: url)
request.setValue("quickstart-QUdJIGlzIGNvbWluZy4uLi4K", forHTTPHeaderField: "api-key")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body = ["text": "Donald Trump"]
let bodyData = try? JSONSerialization.data(withJSONObject: body, options:[])
request.httpMethod = "POST"
request.httpBody = bodyData
URLSession.shared.dataTask(with: request){ (data, responce, error) in
print(responce!)
if let error = error {
print(error)
} else if let data = data {
print(data)
}
}.resume()
I get status code 400. Don't get deep into my optionals unwrapping and so on. Just tell what am I doing wrong? Why curl works and my swift code doesn't?
UPDATE
tried the solution from the suggested question/answer concerning multipart form-data, still not working. Please take a look
var request = URLRequest(url: url)
let boundary = UUID().uuidString
request.setValue("quickstart-QUdJIGlzIGNvbWluZy4uLi4K", forHTTPHeaderField: "api-key")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let body = ["text": "Donald Trump"]
var data = Data()
for(key, value) in body{
// Add the reqtype field and its value to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
data.append("\(value)".data(using: .utf8)!)
}
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
request.httpMethod = "POST"
//request.httpBody = data
URLSession.shared.uploadTask(with: request, from: data){ (data, responce, error) in
print(responce!)
if let error = error {
print(error)
} else if let data = data {
print(data)
}
}.resume()
Don't be mad with my stupidity!)