0

I would like to submit translation requests to the Watson Translation service from Swift but don't want to use the Swift SDK. (IBM plans to discontinue Pod and Carthage support of the SDK due to many issues it says it cannot resolve but beyond that a full blown SKDK seems like overkill). In the past, I've accessed other Watson services with a post request. However, I can't find any examples on using the translation service without the SDK in the documentation.

There are, however, curl examples so if you can call the API from a terminal window it ought to be possible to call it with some Swift code, however, I am not sufficiently knowledgeable about curl to convert this into Swift calls.

Can anyone suggest how to do this with either a get or post https call or point me in the right direction?

Here is curl from the IBM translation documentation:

curl -X POST --user "apikey:{apikey}" --header "Content-Type: application/json" --data '{"text": ["Hello, world.", "How are you?"], "model_id":"en-es"}' "{url}/v3/translate?version=2018-05-01"

The url seems to refer to a service endpoint such as:

https://api.us-south.language-translator.watson.cloud.ibm.com/v3/translate?version=2018-05-01 and the API key is the one given to the user.

Edit:

Putting the curl into reqbin and selecting Raw gives:

POST /instances/~/v3/translate?version=2018-05-01 HTTP/1.1
Authorization: Basic xxx-xxx-xxx-xxx-xxx
Host: api.us-east.language-translator.watson.cloud.ibm.com
Content-Type: application/json
Content-Length: 63

{"text": ["Hello, world.", "How are you?"], "model_id":"en-es"}

My problem is how to convert that to a Post request that is what is in the header and so forth.

Here is some boilerplate code for a post call that I am trying to adapt. It compiles and runs in Swift, however, the API is not allowing authorization (returns 401 Error) as the request is not properly formed.

Thanks for any suggestions on how to convert the CURL into a Post request.

Method with boilerplate code:

 func postPhraseToTranslate (message:String,completion:@escaping (_ response:MyTranslation
        let watsonurl: String =  "https://api.us-south.language-translator.watson.cloud.ibm.com/v3/translate?version=2018-05-01 "  
        let parameters = ["text":message]
        guard let parametersJson = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {//open 2
            //print("")
            return
        }
      
        let username = "xxx-xxx"
        let password = "xxx-xxx-xxx-xxx-xxx-xxx-xxx"
        
        let authString = username + ":" + password
        guard let authData = authString.data(using: .ascii) else {//open 2
           
            return
        }//close 2
        
        let authValue = "Basic " +
            authData.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
        
        let url = URL(string: watsonurl)!
        var request = URLRequest(url: url)
        request.setValue( authValue, forHTTPHeaderField: "Authorization")
       
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        
        request.httpBody = parametersJson
        let task = URLSession.shared.dataTask(with: request) { //open 2
            data, response, error in
            guard let data = data, error == nil else {                                           
               // print("network error=\(error)")
                return
            }
print("got back the translation")
      
         task.resume()
 
    }

Thanks for any suggestions on how to convert the CURL to a Swift Get or Post call:

user1904273
  • 4,562
  • 11
  • 45
  • 96
  • It's really just a matter of making an HTTP request using `URLSession` and handling the response. You're off to a good start with that code. – Mike Taverne Jan 01 '21 at 23:40
  • The issue is configuring the request based on Curl. See edit above. – user1904273 Jan 02 '21 at 03:33
  • According to the docs https://cloud.ibm.com/apidocs/language-translator you are supposed to send the literal “apikey” as the username, followed by colon and your API key. What did you send as the username? – Mike Taverne Jan 02 '21 at 05:46
  • It does say --user "apikey:{apikey}" in the CURL that I fed to Reqbin. However, Reqbin converted that curl to Authorization: Basic xxx-xxx-xxx-xxx-xxx. The crux of my problem is that I don't really understand the correspondence between a CURL and an http POST request and in turn how to consruct the Post request properly using URLRequest. Do you mind if I delete this question? I am going to try to create a more narrow question focused on just on that sequence. – user1904273 Jan 02 '21 at 14:06
  • Found one SO question on this https://stackoverflow.com/questions/46779004/convert-curl-to-urlrequest – user1904273 Jan 02 '21 at 14:17
  • In your code, you are using some values for username and password, and then encoding it. What values are you using? Are you following the docs? You could just copy the encoded value that Reqbin created, append it to the word “Basic” and set it as the Authorization header. – Mike Taverne Jan 02 '21 at 21:14

0 Answers0