Alamofire using query parameters status 500 - json

I'm calling an Api route to get branches of a local store using longitude, latitude & radius. The api route is working just fine on postman. Using Alamofire it is replying internal server error 500. I doubt the issue is in the parameters but i just tested everything and every combination with no success.
Here is my HTTP request:
let branchesRoute = "geo/services/"
//Get branches within location radius
func getBranchesWithRadius (serviceID: Int, location: CLLocation, completion: #escaping (_ status:Bool, _ error:Error?, _ msg:String?, _ branches:NSArray?) ->())
{
let route = URL(string:branchIp + branchesRoute + String(serviceID) + "/branches")
print(route)
let header: HTTPHeaders = [
"Content-Type":"application/json",
"auth-token": Helper.shared.getApiKey()//"\(Helper.shared.getApiKey())"
]
let params: Parameters = [
"longitude" : location.coordinate.longitude,
"latitude" : location.coordinate.latitude,
"radius" : Helper.shared.getRadius()
]
print(params)
Alamofire.request(route!, method: .get, parameters: params, encoding: JSONEncoding.default, headers: header)
.validate(statusCode: 200..<300)
.responseJSON { (response) in
switch response.result {
case .success( _):
let json = response.result.value!
// let swiftyJson = JSON(json)
completion(true, nil, nil, json as? NSArray)
// print(json)
case .failure(let err):
print(err)
if response.response?.statusCode == 401 {
completion(false,err,"Unauthorized",nil)
} else {
completion(false, err, "Error getting branches",nil)
}
}
}
}
This is the route im calling from postman:
http://100.100.70.185:9090/geo/services/3/branches?longitude=31.331358000000002&latitude=30.082763&radius=1000000
When i used print() command in swift these were my results:
print(params) = ["longitude": 31.331358000000002, "latitude": 30.082763, "radius": 100000]
print(route) =
Optional(http://100.100.70.185:9090/geo/services/3/branches)
Regarding the Optional i'm just unwrapping it route!
Regarding the ip address i wrote here are not the real ones that i use in case you tested and it didn't work out.

The actual issue is in encoding and you have to use the correct ParameterEncoding depending on your API implementation.
Use URLEncoding if the Content-Type HTTP header field of an encoded request with HTTP body is set to application/x-www-form-urlencoded; charset=utf-8
-
Use JSONEncoding if the Content-Type HTTP header field of an
encoded request is set to application/json
-
Use PropertyListEncoding if the Content-Type HTTP header field of
an encoded request is set to application/x-plist

Related

How to send json body in get request

I know sending json body in get request is violating http rules, however according to client's requirement the server is accepting json body in get request.so i want to send json body in my get request using alamofire.
i tried various parameter encoding types.nothing worked.
func listNews( withCompletionHandler:#escaping (_ status:Bool, _ message: String, _ yearLevels: JSON) -> Void){
let parameters = [
"month": "07",
"year": "2019",
"record_start": 0,
"record_offset": 100
] as [String : Any]
let headers = [
"Content-Type": "application/json"
]
let url = STAFF_SERVICE_URL+"staff/2/news?api_key=\(api_key)"
print("URL > \(url)")
Alamofire.request(url, method: .get,parameters:parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
let statusCode = response.response?.statusCode
print(statusCode ?? "Success Error Code")
if(statusCode==200){
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar)
withCompletionHandler(true,"Success",swiftyJsonVar)
}else if(statusCode==400){
withCompletionHandler(false,"System Error. Please try again later.",JSON.null)
}else{
withCompletionHandler(false,"System Error",JSON.null)
}
}
}
i expect array of json objects in response. but the actual output is time out error
Actually you should change encoding method for get request. You have set encoding: JSONEncoding.default. Instead of that, use encoding: URLEncoding.default.
Second thing, if you are sending parameters in json body, then send all parameters instead of some sending with body and some in url. So, your api_key=\(api_key) should be in json body.
I hope this will fix your issue.

Alamofire - POST request with JSON giving 301

I want to send POST request with JSON, I'm expecting JSON object with auth_token and refresh_token in response. My code looks like this:
let headers: HTTPHeaders = [
"Authorization": "Basic " + data.toBase64() //data is just string needed for authentication
]
// this should be a JSON
let parameters = [
"code": self.code,
"grant_type": "authorization_code",
"redirect_uri": "populi://callback"
]
Alamofire.request("https://populi.pl/api/v1/auth/token", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseString { response in
print(response.request)
print("\n3 RESPONSE : \(response)")
print("\n3 POST : \(response.response)")
print("\n3 DATA : \(response.data)")
print("\n3 RESPONSE RESULT : \(response.result)")
print("\n3 RESPONSE RESULT VALUE : \(response.result.value)")
print("3 ERROR : \(response.error)")
}
Yeah, I print a lot of things, that's because I'm new to networking.
In response I'm getting 301 moved permanently. Why? I have no idea what's wrong. Is this wrong JSON in parameters or maybe something with redirecting? I should get 200 and JSON in response.
try this
func getData(){
let todoEndpoint: String = Your url
let params: Parameters = [yor parameters]
let headers: [String : String] = [
"Content-Type": "application/x-www-form-urlencoded",
]
Alamofire.request(todoEndpoint, method: .post, parameters: params,headers: headers)
.responseJSON { response in
switch response.result {
case .success:
let json = JSON(response.result.value as Any)
print(json)
break
case .failure(let error):
print(error)
}
}
}
I solved this with "/" at the end of request URL.
I was using URLSession for requests and was getting 301 for 1 request
then I tried Alamofire and still got the same response and at the end, I figured out that issue was that I was not appending / at the end of endpoint

not receiving json Data in Alamofire request with http body

Im using the following code to send a POST request to the web server with an http parameter, in order to receive the JSON Data
Alamofire.request(.POST,myURL, parameters: [:], encoding: .Custom({
(convertible, params) in
var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
mutableRequest.HTTPBody = "MyBody".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}))
ive got it from stackoverflow : POST request with a simple string in body with Alamofire
but im not receiving any data.
im using swift 2.3 and alamofire 3.5.
Any help?
simple POST call with Alamofire4 & Swift3 :
let url: String = "https://example.com"
let parameter = ["X": "10", "Y": "20"]
Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil)
.responseJSON { (response) in
let result = response.result.value
print(result)
}
simple GET call to see some JSON result :
let url: String = "https://example.com"
Alamofire.request(url)
.responseJSON { response in
let result = response.result.value
print(result)
}

Could not decode token: The token ###

I'm using Laravel 5.3 as an API for my iOS app. When I try to make HTTP calls with headers and parameters I get this 401 error:
message = "Could not decode token: The token
\"Optional(\""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhcL3Bvc3RMb2dpbiIsImlhdCI6MTQ4MDUzNzQxOCwiZXhwIjoxNDgwNTQxMDE4LCJuYmYiOjE0ODA1Mzc0MTgsImp0aSI6ImMyZmYxNzI5N2U5OGU4MzkzYzZkZWRmNTZlN2ZkMzNkIn0.u6sQqlq5k-B5jhZ7EymkXLlcTIQ-i7X_83an5irwTss\"" is an
invalid JWS";
"status_code" = 401; }
This is the code that makes the HTTP request:
let headers = ["Authorization":"Bearer \(token)"]
request(url! , method: .get, parameters: nil, encoding: JSONEncoding.default , headers: headers )
.responseJSON { response in
print("RESPONSE \(response)")
I did some googling and found a package to encode JWT called JWTDecode.swift. Here is the link to the code: https://github.com/auth0/JWTDecode.swift. I still couldn't figure out how to solve this issue.
change
let headers = ["Authorization":"Bearer \(token)"]
to something like
guard let token = token else { return }
let headers = ["Authorization":"Bearer \(token)"]
otherwise you are sending Optional(<token>) instead of <token>.

OpenSecret API only returning text/html

I am attempting to access the open secret API (https://www.opensecrets.org/api) from a swift created iPhone App.
I am using AFNetworking GET request as follows:
func getContributors(congressperson: congressPerson!, success: ([NSDictionary]) -> (), failure: (NSError) -> ()){
let parameters = [
"cid": congressperson.crpId,
"output": "json",
"apikey": opensecretApiKey,
"cycle": "2016"] as NSDictionary
GET("api/?method=candContrib", parameters: parameters, progress: nil, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in
let results = response!["results"] as! [NSDictionary]
print("here success")
success(results)
}) { (operation: NSURLSessionDataTask?, error: NSError) -> Void in
print("here fail")
failure(error)
}
}
Although I am requesting an output of json, this code results in the error:
Request failed: unacceptable content-type: text/html
Am I doing something wrong in this request? Anyone know how to force it to return as json?