0

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!)

gay0rgy
  • 1
  • 1
  • 1
    By using `try?` and not `do/try/catch`, you're throwing away any chance at seeing an error. Also, unless there's a compelling reason not to, I'd use `Codable` instead of `JSONSerialization` to do the decoding work. – jnpdx Jul 11 '21 at 20:04
  • Yes, I understand this issues. I am just playing around with data fetching for now, so I don't bother too much with proper error handling etc. – gay0rgy Jul 11 '21 at 20:07
  • 1
    The curl example is multipart form-data. Your Swift code is not. – matt Jul 11 '21 at 20:09

0 Answers0