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
Related
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)
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
Spent hours on this with no success.
I'm using Alamofire to make a HTTP POST to back end server which requires some parameters to be supplied with request.
I'm successfully hitting the server but the server is responding with a 500 stating no parameters were sent?
I've tried most of the SO solutions (changing the encoding type, setting parameters as NSDict, etc) but with no success.
Any help greatly appreciated.
PS its Swift3 with Alamofire 4
Code:
let params: [String: String] = ["deviceID": "Some device ID",
"email": "email","password": "password","userid": "1234",
"username":"gordon"]
let request_params: Parameters = ["LoginUser" : params]
let url = "https://myserver/LogIn" as String
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.default, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(response.response)
case.failure(let error):
print("Failed!",error)
}
}
Update:
Below is the body of the POST, it looks like this is where the problem exists:
Alamofire POST body (from above code) -
(LoginUser%5BdeviceID%5D=12345&LoginUser%5Bemail%5D=gordon%40test.com&LoginUser%5Buserid%5D=00000000-0000-0000-0000-000000000000&LoginUser%5Bpassword%5D=testPassword&LoginUser%5Busername%5D=gordon)
It should be something like (ignoring the encoding values):
This is a functional post body-
LoginUser=%7B%22deviceID%22%3A%22%22%2C%22email%22%3A%22gordon%40test.com%22%2C%22password%22%3A%22testPassword%22%2C%22userid%22%3A%2200000000-0000-0000-0000-000000000000%22%2C%22username%22%3A%22gordon%22%7D
As you can see the Alamofire post seems to concatenate the LoginUser to start of each attribute? Also missing the LoginUser= at start??
Try to use JSONEncoding.default instead of URLEncoding.default
OK so I got this working with the below code, would be very interested in understanding if this is the most efficient means of posting param?
let params: NSMutableDictionary? = ["deviceID": "someDeviceID",
"email": "emailAddress","password": "aSecret","userid": "12345",
"username":"gordon"]
let url = "https://serverAdrress" as String
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json: NSString! = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
let request_params: Parameters = ["LoginUser" : json as Any]
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.httpBody, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))
print(response.response)
case.failure(let error):
print("Not Success",error)
}
}
I want to use Alamofire to retrieve a bearer token from Web API but I am new to ios and alamofire. How can I accomplish this with Alamofire?
func executeURLEncodedRequest(url: URL, model: [String : String]?, handler: RequestHandlerProtocol) {
addAuthorizationHeader()
Alamofire.request(.POST,createUrl(url), parameters: model, headers: headers,encoding:.Json)
}
Well you don't really need Alamofire to do this (it can be simply done using a plain NSURLRequest) but here goes:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
"myParameter": "value"
]
let url = NSURL(string: "https://something.com")!
Alamofire.request(.POST, url, parameters: parameters, headers: headers, encoding: .URLEncodedInURL).response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
I think that the headers can be omitted since alamofire will append the appropriate Content-Type header. Let me know if it works.
You can also find a ton of specification with examples here.
Alamofire 4.7.3 and Swift 4.0 above
As per the documentation for POST Request With URL-Encoded Parameters
let parameters: Parameters = [
"foo": "bar",
"val": 1
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&val=1
Alamofire 5.2
let parameters: [String: [String]] = [
"foo": ["bar"],
"baz": ["a", "b"],
"qux": ["x", "y", "z"]
]
// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
// HTTP body: "qux[]=x&qux[]=y&qux[]=z&baz[]=a&baz[]=b&foo[]=bar"
Here is example code that should work with Alamofire 4.x and Swift 3.x as of August 2017:
let parameters = [
"myParameter": "value"
]
Alamofire.request("https://something.com", method: .post, parameters: parameters, encoding: URLEncoding()).response { response in
print(response.request)
print(response.response)
print(response.data)
print(response.error)
}
There is no need to set the content-type header explicitly, as it is set by Alamofire automatically.
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",
.....
}
}