How to add Alamofire URL parameters - swift

I have a working scenario using Postman passing in URL parameters. Now when I try to do it via Alamofire in Swift, it does not work.
How would you create this url in Alamofire?
http://localhost:8080/?test=123
_url = "http://localhost:8080/"
let parameters: Parameters = [
"test": "123"
]
Alamofire.request(_url,
method: .post,
parameters: parameters,
encoding: URLEncoding.default,
headers: headers

The problem is that you're using URLEncoding.default. Alamofire interprets URLEncoding.default differently depending on the HTTP method you're using.
For GET, HEAD, and DELETE requests, URLEncoding.default encodes the parameters as a query string and adds it to the URL, but for any other method (such as POST) the parameters get encoded as a query string and sent as the body of the HTTP request.
In order to use a query string in a POST request, you need to change your encoding argument to URLEncoding(destination: .queryString).
You can see more details about how Alamofire handles request parameters here.
Your code should look like:
_url = "http://localhost:8080/"
let parameters: Parameters = [
"test": "123"
]
Alamofire.request(_url,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: headers)

If you want your parameters to be used in querystring, use .queryString as URLEncoding, as in:
(I assume you have headers somewhere)
let _url = "http://localhost:8080/"
let parameters: Parameters = [
"test": "123"
]
Alamofire.request(_url,
method: .post,
parameters: parameters,
encoding: URLEncoding.queryString,
headers: headers)
This form is suggested by Alamofire author because it's more coincise to the other, see screenshot:
See original here

Related

Alamofire syntax for ecobee request

I'm trying to find the correct syntax for calling ecobee's API from Swift 4 using Alamofire.
Their cURL example:
curl -H "Content-Type: text/json" -H "Authorization: Bearer ACCESS_TOKEN" 'https://api.ecobee.com/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"","includeRuntime":true\}\}'
The closest I've been to a solution is this
func doRequest() {
guard let url = URL(string: "https://api.ecobee.com/1/thermostat?format=json") else { return }
let parameters: Parameters = [
"selection": [
"selectionType": "registered",
"selectionMatch": ""
]
]
let headers: HTTPHeaders = [
"Content-Type": "text/json",
"Authorization": "Bearer \(core.accessToken)"
]
let req = AF.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
print("Error:", response.error?.localizedDescription ?? "no error")
print("Data:", String(data: response.data!, encoding: .utf8)!)
}
debugPrint(req)
}
When I run this, the call ultimately fails with status code 408, a server timeout.
When I change the HTTP method to use .post, the call completes, but the response is an internal status 3 with message "Update failed due to a communication error."
Can anyone help me figure out what I'm doing wrong before I waste another day trying to hack my way through it?
Ecobee's request format is a bit bizarre, as it uses form encoded parameters, but one of the values is a JSON encoded body. You'll have to do a little bit of prep work, as Alamofire doesn't naturally support something like this. This is just sample code, you'll need to do the work to make it safer.
First, encode the JSON parameters and get the String value:
let jsonParameters = ["selection": ["selectionType": "registered", "selectionMatch": ""]]
let jsonData = try! JSONEncoder().encode(jsonParameters)
let jsonString = String(decoding: jsonData, as: UTF8.self)
Then, create the actual parameters and headers values:
let parameters = ["format": "json", "body": jsonString]
let token = "token"
let headers: HTTPHeaders = [.authorization(bearerToken: token), .contentType("text/json")]
let url = URL(string: "https://api.ecobee.com/1/thermostat")!
And make the request:
AF.request(url, parameters: parameters, headers: headers).responseJSON { response in ... }

Multiple Arguments in AlamoFire.Request

I am trying to access Spotify's web API. I am currently using Alamofire to request the search operation which only requires a token. However, I could not figure out why it won't let me send multiple arguments.
let headers = ["Authorization": "Bearer {your access token}"]
var searchURL = "https://api.spotify.com/v1/search?q=Odesza&type=track"
AF.request(.GET, url, headers: headers)
.responseJSON { response in
debugPrint(response)
}
Alamofire does a great job of formatting parameters to a request url. Just as you pass parameters with the .post method to the AF request function you also pass a parameters [string : any] to the AF request for .get methods as well. The difference is .post will put the parameters in the request.body/data vs. .get will format the parameters into the url with the ?q=my_search_string
something along the lines of this:
Let params: [string :any] = ["q": "odesza", "type":"track"]
AF.request(.GET, url, parameters:params, headers: headers) .responseJSON { response in debugPrint(response

Json key/value incorrectly formatted

Trying to login to a web service as such:
let parameters: Parameters = [
"Password":password,
"Username":username
]
var headers:HTTPHeaders = commonHeaders()
headers["Content-Type"] = "application/json;charset=UTF-8"
Alamofire.request(url!, method:.post, parameters:parameters, headers:headers).responseJSON { response in
....
}
Somehow, my parameters end up on the server side as
"Username=xxx&Password=yyy"
where
{"Username":"xxx","Password":"yyy"}
is expected
This must be something simple, but I hope you can help me
Add the type of encoding you want your parameters to be in your request, Default is .URLEncoding. So, your parameters are going like "Username=xxx&Password=yyy"(appended into url)
Add the parameter json encoding to your request:
Alamofire.request(url!, method:.post, parameters:parameters, headers:headers, encoding: JSONEncoding.default)

Alamofire POST request URL

Suppose i have a URL "http://aewfwfpi.staginwwedwfg.dewfewf.io/mobile/v1/network/station/10/timetablesss"
where 10 in the above URL is the stationId and can be any number .
How can i POST a request with changing parameter(StationId) in the URL using alamofire?
Should i add it in Parameter section?
Please help
Currently am calling it statically like below:-
Alamofire.request(
"http://aewfwfpi.staginwwedwfg.dewfewf.io/mobile/v1/network/station/10/timetablesss",
parameters:nil,
headers: nil)
var id = 123
var yourURL = "http://aewfwfpi.staginwwedwfg.dewfewf.io/mobile/v1/network/station/\(id)/timetablesss"
use \(variableName) to insert variables or constants in a string
Headers is where you specify the format of the content that you want to send and receive.
example of headers:
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type": "application/json"
]
Parameters is where you put the data that you want to send (POST)
example of parameters:
let pararameters: [String, Any] = [
"name": name as String,
"id": id as Int,
]
To do a POST request, add the parameters to the body of the request and not the url itself.
Something like below is what you must follow:
let parameters: Parameters = ["parameter-name": parameterValue]
let headers = ["Content-Type":"application/json"]
Alamofire.request("<your post url>",method: .post, parameters: parameters, encoding: JSONEncoding.default,headers: headers)
.responseJSON { response in
print(response)
// Do anything you like with the response here
}

Is there a simple way to send a key, value in Alamofire in the body NOT param?

I need to send a list of strings under a key in the body. Alamofire makes parameters super simple but I can't figure out how to do it in the body of the request. This doesn't help me since its for a simple string and I can't figure out how to make it work for an array of strings: POST request with a simple string in body with Alamofire . This one is titled about a JSON body but the answer is giving them as params Alamofire 4, Swift 3 and building a json body . Does anyone have an answer or a link to something that actually solves my problem?
Code as requested:
var params = ["phone_numbers": [6314560046, 8458200476]] as [String: Any]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON() { response in
With Alamofire, the parameters are the body of the request. This creates your key with value of array of strings:
let parameters = ["Key": ["String1", "String2", "String3"]]
Then use the parameters in making the request:
Alamofire.request(URL, method: .post, parameters: paramaters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
}