I am consuming a Login API from my node.js server deployed on EB. It works completely file in Postman when I do a post request to :
Secure://mydomain dot com/login
Body :
{
"email" : email,
"password" : password
}
But I am trying to do it in Swift and it keeps throwing errors. Here is my code :
func loginFunction()
{
let loginURL = "login URL"
if let email = emailField.text, let password = passwordField.text
{
let login = [
"email" : email as String,
"password" : password as String]
let headers : HTTPHeaders = ["Content-Type" : "application/json"]
AF.request(URL.init(string: loginURL)!, method: .post, parameters: login,
encoding: JSONEncoding.default, headers: headers).responseString { (response) in
print(response.result)
}
}
}
I keep getting 502 Bad Gateway error, even though it works okay when I test this in Postman. What am I doing wrong?
Related
I'm attempting to access an api using my username and api key. An example they give, which I believe is .NET, is:
Public Sub GET_Products()
Dim request As HttpWebRequest = WebRequest.Create("https://api.ssactivewear.com/v2/products/?style=39")
request.Method = "GET"
request.Credentials = New NetworkCredential("YOurCustomerNumber", "YourAPIKey")
Try
Dim response As HttpWebResponse = request.GetResponse
Dim StreamReader As New StreamReader(response.GetResponseStream())
Result = StreamReader.ReadToEnd
If response.StatusCode = HtppStatusCode.OK Then
Products = serializer.Deserialize(Of List(Of Sku))(Result)
Else
End If
Catch ex As Exception
End Try
End Sub
I've used the following to test the request for a response:
guard let url = URL(string: "https://api.ssactivewear.com/v2/products/") else { return }
let username = "myusername"
let password = "myapikey"
AF.request(url).authenticate(username: username, password: password).responseJSON { response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("HeaderFields: \(String(describing: response.request?.allHTTPHeaderFields))")
if let json = response.value {
print("JSON: \(json)")
//self.responseText.text = "JSON: \(json)"
}
if let error = response.error {
print("ERROR: \(error.localizedDescription)")
//self.responseText.text = "ERROR: \(error.localizedDescription)"
}
}
This fails authentication because no authentication header is sent. I believe I read this is expected behavior but didn't find a solution.
create APIMiddle class:
class APIManager
{
class func headers() -> HTTPHeaders
{
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"Accept": "application/json"
]
return headers
}
}
your api call:
let request = AF.request(path, method: .post, parameters: params, encoding: JSONEncoding.default, headers: APIManager.headers(), interceptor: nil)
request.responseDecodable(of: UserModel?.self) {(resposnse) in
let user = resposnse.value
print(user)
}
Alamofire's authenticate method adds a URLCredential to the Request which is used to respond to server challenges. If the server never sends a challenge for those credentials, the credentials will never be used. api.ssactivewear.com appears to use HTTP Basic auth, which should work fine, but I couldn't find any specific documentation about that. There may be other requirements to properly make a request to the API. I suggest you investigate those requirements as well as the actual network traffic being sent to see what's actually happening.
Used techs
Django 2 with Django Rest Framework (Drf)
JWT for authentication
iOS/Swift4/Alamofire
here the issue.
django will recieve Alamofire's POST request as GET request.
iOS/swift4 code.
static func getToken (){
let username = "root"
let password = "DAMnShEIsSoHo1!t"
let parameters: [String: Any] = [
"username" : username,
"password" : password,
]
let url = ApiController.baseServerUrl + "api-token-auth"
print("URL :: \(url)")
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print("RESPONSE :: \(response)")
}
}
log from iOS
RESPONSE :: SUCCESS: {
detail = "Method \"GET\" not allowed."; }
log from django server
my.ip.address - - [04/Mar/2018:07:55:32 +0000] "GET /api-token-auth/ HTTP/1.1" 405 40 "-" "Foodle/0.0.1 (com.domain.Appname; build:2;
iOS 11.2.0) Alamofire/4.6.0"
what shall i do from here?
ps. it works fine on PostMan, DRF web console and CURL
ALWAYS add / at the end of your endpoint.
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.
Hello World,
I come to you because, I try to send headers with parameters in the same function like this:
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: headers, parameters: parameters)
but maybe you already knew just headers are sent.
I tried also this way:
let manager = Alamofire.Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
"Authorization": token]
manager.request(.PUT, "http://192.168.99.100:3030/users/\(identity)", parameters: parameters, encoding:.JSON)
but the headers are not sent..
What is the easy way to implement headers in alamofire?
Thanks by advance ;-)
regards,
set headers in dictionary just like other parameter and pass it in headers. for example
let Auth_header = [ "Authorization" : token ]
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters)
You can check details HTTP Basic Authentication
HTTP Basic Authentication
The authenticate method on a Request will automatically provide an NSURLCredential to an NSURLAuthenticationChallenge when appropriate:
let user = "user"
let password = "password"
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.responseJSON { response in
debugPrint(response)
}
Depending upon your server implementation, an Authorization header may also be appropriate:
let user = "user"
let password = "password"
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers)
.responseJSON { response in
debugPrint(response)
}
I already did what you said in the first comment but anyway there are just the headers sent:
let parameters : [String : NSString] = [
"username": username,
"email": email,
"currentPassword": currentpassword,
"newPassword": newpassword]
let Auth_header = [ "Authorization" : token ]
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters)
Resolved: The probleme was that I did't give the encoding in parameter
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters, encoding: .JSON)
Thanks to EI Captain
I am using alamofire for api calling.
here is my code
func signup()
{
let url = "#####################"
let param =
[
"mobile_number" : "9999996586",
"email_address" : "rakholiya#gmail.com",
"password" : "123456",
"api_key" : "4042328"
]
request(.POST, url, parameters: param, encoding: .JSON).responseJSON { (response:Response<AnyObject, NSError>) -> Void in
print(response.result.value)
}
}
Now it's giving response as unauthorised access. So I have to send the "apikey"in query string as get parameter and other data as POST so how can I do this?? I know this may be silly question. but I am new to developing so plz help me.
You can pass your apikey in url which will behave like get
let url = "www.google.com/signup.php?apikey=xyz" //apikey is your key and xyz is your value
And rest of your work will be same, don't need to change it.
You have to pass param at the end of the url string to send complete request to the server like following like.
let url = "www.yahoo.com/signup.php?apikey=abc"
rest of the parameter you can pass as same you have already done.
let param =
[
"mobile_number" : "9999996586",
"email_address" : "rakholiya#gmail.com",
"password" : "123456"
]
request(.POST, url, parameters: param, encoding: .JSON).responseJSON { (response:Response<AnyObject, NSError>) -> Void in
print(response.result.value)
}
i hope this will help you.