Alamofire HTTP requests fails - ios

I made some HTTP requests using Alamofire. Some request has been succeeded and some are failed.
error is Invalid value around character 0.
Failed request gave me above error.
bellow i have mentioned a sample code which failed.
let parameters = ["amount": ["10"], "payment_method": ["paypal"], "date": ["2015-11-25"], "details": ["Payment description"]]
let headers = [
"Accept": "*/*",
"Content-Type": "application/json"
]
let url = "https://livetest.somedomain.com/api/invs/LAT1j5da99PdPg/payments?auth_token=pbtTEPNki3hUhGBuPX3d"
Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON, headers: headers)
.responseJSON { response in
let results = response.result
print(results)
print(response.debugDescription)
}
Please help me to find the issue

This issue was happened because of wrong format of JSON passing. Then i changed the parameter as follows
let parameters = ["payment":["amount": "100" , "payment_method": "check", "date": "2015-11-25", "details": "Payment description dimuth Lasantha"]]
Now it passes the correct format which is
{
payment: {
"amount" : "100",
"payment_method" : "check",
.....
}
}

Related

Getting bad request error in FedEx OAuth Swift

I am trying to authorised FedEx token but getting 400 error.
FedEx Developer link : https://developer.fedex.com/api/en-us/catalog/authorization/v1/docs.html#operation/API%20Authorization
Code Snippet :
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
"grant_type":"client_credentials",
"client_id":"***********************",
"client_secret":"***********************"
] as [String : Any]
Alamofire.request("https://apis-sandbox.fedex.com/oauth/token", method: .post, parameters:parameters,encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
Getting Error :
{
errors = (
{
code = "BAD.REQUEST.ERROR";
message = "Missing or duplicate parameters. Please modify your request and try again.";
}
);
transactionId = "b1d9d540-ed29-49fd-a4c2-907718e918c2";
}
From the FedEx documentation you can see that the parameters need to be sent as form-urlencoded.
And indeed, you have specified this in your headers, but then you have used a JSON encoder, so a JSON document will be sent.
Rather, use
Alamofire.request("https://apis-sandbox.fedex.com/oauth/token",method: .post, parameters: parameters, encoder: URLEncoding.default, headers: headers)

Onfido sandbox error 422 Unprocessable Entity Validation

I'm trying to create a check in Onfido sandbox environment and it's working fine when I use curl or python code while I'm receiving error 422 when I do the same request using swift from iOS.
here is the code that is confirmed to work in python:
def identity_check(self, applicant_id: str) -> dict:
return self._post(
'applicants/{}/checks'.format(applicant_id),
data={
'type': 'express',
'reports[][name]': 'identity',
'reports[][variant]': 'kyc',
}
)
and this is the swift code that gives me error 422:
func executeCheck() {
let headers: HTTPHeaders = [
"Authorization": "Token token=\(token)",
"Accept": "application/json",
]
let parameters: [String: Any] = [
"type": "express",
"reports[][name]": "identity",
"reports[][variant]": "kyc"
]
Alamofire.request(
"https://api.onfido.com/v2/applicants/\(self.applicantId)/checks",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: headers).validate().responseJSON { (response: DataResponse<Any>) in
guard response.error == nil else {
return
}
self.saveCompletedDocumentState()
}
}
This particular issue is to do with a misuse of Alamofire, particularly on the nesting of 'reports[][name]': 'identity'. You should nest by having a sub object, "reports": ["name": "identity"].
However, the recommended approach to start onfido checks is to do them on the backend.
Also, any questions with api can be answered by Onfido Tech Support here api#onfido.com

Alamofire POST Bad Request

I'm trying to make a post request to my server through Alamofire but it returns a bad request saying that parameters are badly formed. Same requests is working in postman and swagger.
Here is the code:
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("https://thankyouposta.com/api/auth", method: .post, parameters: params, encoding: URLEncoding.default, headers: R.Api.headers).responseJSON { response in
switch response.result {
case .success(let value):
// ...
case .failure(let error):
// ...
}
}
Update 1
Parameters needs to be sent as form url encoded body
Update 2
Value of R.Api.headers is
["Content-Type" : "application/x-www-form-urlencoded"]
If you want to send request as a form-urlencoded, you should put it as a headers and change your encoding:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("your_url_here", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
}
The backend was an IIS server with redirection to Tomcat. I've excluded IIS and make the requests directly to Tomcat and it is working now. As I understood, the problem was in delivering the request from IIS to Tomcat.
Solved

{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; } In swift

I am trying with this but every time I will get
{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; }
Request String:
let headers = [ "Content-Type" : "application/x-www-form-urlencoded"]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["grant_type":"authorization_code","code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"387376833747-12pbtud9tepr4di0insdhc0d4qpf5e9m.apps.googleusercontent.com","client_secret":"xOacVhLavM9fH8SpOK4I2dRJ","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Also try with passing request parameter like this but still doesn't work for me.
You can't send appended parameter with url while post request.
Pass parameter as below this
let headers = [ "Content-Type" : "application/x-www-form-urlencoded","grant_type" : "authorization_code"" ]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"apps.googleusercontent.com","client_secret":"","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
These error invalid_request occurs only below cases so please check with your server side what is missing or invalid.
The request is missing a required parameter, includes an unsupported
or invalid parameter value, repeats a parameter,includes multiple
credentials, utilizes more than one mechanism for authenticating the
client, or is otherwise malformed.

Twitter API in SWIFT via Alamofire

I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply cant get it working
My Code looks like:
func TWITTER_getPosts(username:String){
let headers = [
"screen_name": "username",
"authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
"include_rts": "false"
]
Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I Always end in a
errors = (
{
code = 215;
message = "Bad Authentication data.";
One of the parameters for the request method is incorrect.
If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
headers: headers should be the way to go.

Resources