How to send json body in get request - json

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.

Related

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

Alamofire using query parameters status 500

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

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)
}

Alamofire Mailchimp API 3.0 subscribe

I am trying to subscribe new user to Mailchimp list using Alamofire.
Problem starts when I'm trying to subscribe new user with .post method and JSONObject as a parameter:
func subscribeMail(){
let credentialData = "<my_api_key>".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]
let url = "https://us11.api.mailchimp.com/3.0/lists/<my_list_id>/members/"
let jsonObj: [String: AnyObject] = [
"mail_address" : "testMailAddress#gmail.com" as AnyObject,
"status" : "subscribed" as AnyObject,
]
let valid = JSONSerialization.isValidJSONObject(jsonObj)
print(valid)
Alamofire.request(url, method: .post, parameters: jsonObj , encoding: URLEncoding.default , headers: headers).responseJSON{response in
if response.result.isFailure {
print("Failed")
}
else if (response.result.value as? [String: AnyObject]) != nil {
print(response)
}
}
}
I get back status code 400:
SUCCESS: {
detail = "We encountered an unspecified JSON parsing error.";
instance = "";
status = 400;
title = "JSON Parse Error";
type = "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/";
}
In Mailchimp documentation:
JSONParseError
We encountered an unspecified JSON parsing error.
This error means that your JSON was formatted incorrectly or was considered invalid or incomplete.
As you can see I am checking my jsonObj if its valid. So I dont get this parsing error..
In Mailchimp API 3.0 its written that just email_address and status fields are needed to subscribe new mail.
If I try to to send request with Alamofire using .get method with some mail address that is already subscribed, everything works fine, I can receive all data from Mailchimp.
Is there really problem with my jsonObj or is it somewhere else?
Change the object key from 'mail_address' to 'email_address' and give a try.
let jsonObj: [String: AnyObject] = [
"email_address" : "testMailAddress#gmail.com" as AnyObject,
"status" : "subscribed" as AnyObject,
]
Since you're getting a JSONParseError, your issue is related to the format in which you're sending the parameters.
Try encoding: JSONEncoding.default instead of encoding: URLEncoding.default.

Alamofire 3.0 handle JSON

Sorry for my bad english :)
So here we go. I started to create iPhone Apps in Swift 2.
I would like to use an API. For the Request I have used the Alamofire 3.0 Library. And this works fine, but I am unable to handle the JSON. I tried to use SwiftyJSON but I have no idea how it works. There is my code:
let headers = [
"Content-Type": "application/json"
]
Alamofire.request(.GET, "API URL", headers: headers)
.responseJSON { response in
if response.result.isSuccess {
}
}
I hope someone can help me. ;) Thanks
My latest usage of Alamofire (3.0) and SwiftyJSON (2.3)
let parameters = ["param1" : param, "param2" : "stringParam"] // my params, not required
Alamofire.request(.POST, url, parameters: parameters)
.responseJSON{ response in
guard response.result.error == nil else {
print("Error. \(response.result.error?.localizedDescription)")
return
} // guard close
if response.result.isSuccess {
let post = JSON(response.result.value!) // JSON is stored in post variable
// Another check of result
//if let value: AnyObject = response.result.value {
// let post = JSON(value)
} // if close
} // responseJSON close
Then access the JSON as per the instructions in Github
Hope this helps
Jacko