iosswiftalamofiremashape

How to make an API call(Mashape) with the below parameters using Alamofire?


Im building a small app in Swift 3 for iOS and the api I'm consuming for getting the data for the app has a cURL request. The cURL request of the API is as follows:

//        curl -X POST --include 'https://myApi.mashape.com/' \
//        -H 'X-Mashape-Key:APIKEY' \
//        -H 'Content-Type: application/json' \
//        -H 'Accept: application/json' \
//        --data-binary '{"parameter1":"value","parameter2":"value"}'

Using Swift and Alamofire, this is the API call I'm making to fetch the data using POST method.

func networkFunction(completed: @escaping DownloadComplete) {


let headers: HTTPHeaders = [
    "X-Mashape-Key":"APIKEY",
    "Content-Type":"application/json",
    "Accept": "application/json"
]
let parameters: Parameters = [
    "parameter1" : "value",
    "parameter2" : "value"
]
Alamofire.request("https://myApi.mashape.com",method: .post,parameters: parameters, headers: headers).responseJSON
    { response in
        
        print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)")
        
        let result = response.result
        print(response.description)
        
        if let dict = result.value as? Dictionary<String , AnyObject> {
            if let parameter1 = dict["parameter1"] as? String {
                self._parameter1= parameter1
      
            }
            if letparameter2 = dict["parameter2"] as? String {
                self._parameter2 = parameter2
                print(parameter2)
            }
        }
    completed()
    }

}

When I do the above I get an error in the console as a bad request. I have tried changing the function call but the result is the same. What is going wrong in the API call above?

Edit: I have added the solution in the answer below.


Solution

  • I found out that the error stemmed from the fact that :

    1. The ordering of the parameters wasn't right
    2. I had omitted adding the JSON Encoding parameter.

    The final call with the changes looks like this :

    Alamofire.request("https://myAPI.mashape.com/beta",method: .post,parameters: parameters,encoding: JSONEncoding.default, headers: headers).responseJSON
            { response in
              ...
              ...
              ...
            }