Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(500) - alamofire

I'm working on Alamofire and I am trying to post a request to the server like this:
func sendRequest () {
print("fire now----------------------------------------------")
let parameters: Parameters = ["user": "001", "name": "josh"]
print(parameters)
let a = Alamofire.request("http://120.77.252.96:8388/", method: .get, parameters: parameters, encoding: URLEncoding.default).validate(statusCode: 200..<500).responseJSON(completionHandler: {responds in
switch responds.result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
case .failure(let error):
print(error)
}}
)
print(a)
}
But I constantly get errors like this:
Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(500)
and when I check the server side, it seems that the body of the request is empty.
Can anyone help me with this? Thanks so much!

I had the same problem my friend and I resolved it by changing the status code from
validate(statusCode: 200..<500)
to
validate(statusCode: 200..<600)
I'm new to Alamofire so I cannot give you an explanation to why or how it works or what the error means.

An explanation of Cyril's accepted answer:
HTTP server functions conventionally return a status code that indicates what happened while processing the request. Alamofire can read this to determine if the response is valid, or an error occured. Depending on how your server was implemented, you can tell Alamofire the range of status codes that you consider to mean a 'valid' response, you do this by giving this range to the validate() function. For example, .validate(statusCode: 200..<500) tells Alamofire that any response with the status code 200 up to 499 should be considered valid, every other code (including 500) should be invalid.

Try to remove request.validate(statusCode: 200..<300)

Tweaked my alamofire version in my pod file and it fixed the issue.
Try downgrading it in your pod file using:
pod 'Alamofire', ~>'4.8.2'

Related

karate.prevRequest does not work inside scenarios tagged #report=false

As an example, this scenario will fail with an error, "cannot convert, not a json string: [type: NULL, value: null]":
#report=false
Scenario: POST request; 200 response
Given url 'http://localhost:8080'
And request { "id": "123" }
When method post
* def requestBody = karate.prevRequest.body
* json requestJson = requestBody
However, if you remove the #report=false tag (or set it to 'true'), the request body is captured just fine.
Is this a bug or am I missing something obvious here?
Thanks!
This has been resolved with v0.9.9
It may be a bug, but can you please use the 1.0 series: https://github.com/intuit/karate/wiki/1.0-upgrade-guide
All development is focusing on that, and as of now you should be able to test 0.9.9.RC4 - and if you still see an issue, please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

make groovy request accept 404 -- Error: hudson.AbortException: Fail: the returned code 404 is not in the accepted range: [[100‥399]]

I'm writing some integration tests for my api.
Now, i want to test an request that returns an 404.
This is what i want, but groovy/hudson always marks my build as failed when i try it.
This is, of course, because 404 is not between the accepted range.
I DO understand the error. The problem is that i don't know how to fix this.
Part of my Groovy file:
def testID = "fakeID"
response = httpRequest acceptType: "APPLICATION_JSON",
contentType: "APPLICATION_JSON",
customHeaders: [[name: 'Authorization', value: token]],
url: server+port+"/exams"+testID
Does anyone know how to make groovy accept this 404?
All help beeing thanked for in advance!
You can use validResponseCodes parameter to specify a range of valid response codes
response = httpRequest acceptType: "APPLICATION_JSON",
contentType: "APPLICATION_JSON",
customHeaders: [[name: 'Authorization', value: token]],
url: server+port+"/exams"+testID,
validResponseCodes: '200:404'
See httpRequest documentation

Alamofire Parse Response Data when validate fails

So the API I'm working with will sometimes send an error message in the response body when a request fails. This is located in response.data. Sometimes it's JSON, sometimes it's a string. I'm using the validate method so result.value is nil when an error occurs.
Is there a way of having Alamofire serialize the data from NSData to a string or for JSON to [ String : AnyObject ] like it would if the response was successful?
I would like to keep using the validate method.
EDIT:
Here's a link to a feature request I started on the Alamofire GitHub project.
https://github.com/Alamofire/Alamofire/issues/1459
There is not currently. I'm actually working on this very feature in Alamofire 4 right now. In Alamofire 3, you'll have to parse the response.data yourself if you get that validation error. In Alamofire 4, you'll at least have access to the response.data at the time of validation as well as be able to customize the Error that is generated by validation.
Most likely what the final solution will be is the ability to check in validation if you know there's going to be an error (checking response status code and headers). Then based on the type of error, you could parse the response.data to extract the error message from the server and throw a VERY SPECIFIC error from validation. This is most likely what the new system will allow. This way you could identify OAuth2 access token errors right in validation and throw your own custom error rather than having to use a convoluted system of response serializers to do it.
Swift 4
If you get an error, you can try parsing the response data as a string or as json.
import Alamofire
import SwiftyJSON
Alamofire.request("http://domain/endpoint", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.validate()
.responseJSON(completionHandler: { response in
if let error = response.error {
if let data = response.data {
if let errorString = String(bytes: data, encoding: .utf8) {
print("Error string from server: \(errorString)")
} else {
print("Error json from server: \(JSON(data))")
}
} else {
print("Error message from Alamofire: \(error.localizedDescription)")
}
}
guard let data = response.result.value else {
print("Unable to parse response data")
return
}
print("JSON from server: \(JSON(data))")
})

Authenticating the cobrand

I created a new developer account and I am having a problem authenticating with the REST API.
POST https://rest.developer.yodlee.com/services/srest/restserver/v1.0/authenticate/coblogin
{ cobrandLogin: 'sbCob*****',
cobrandPassword: '**********' }
the system responds with:
{ Error: [ { errorDetail: 'Internal Core Error has occurred' } ] }
am I doing something wrong?
I am testing the API with Postman and apparently I need to send the params with x-www-form-urlencoded to make it work. Using the default form-data lead to the above mentioned error.
In my case, this was solved by changing the content-type as per http://developer.yodlee.com/Aggregation_API/Aggregation_Services_Guide/Aggregation_REST_API_Reference
require 'rest-client'
module Yodlee
def self.login_to_yodlee
site = self.site_resource
login_hash = {
cobrandLogin: 'yourlogin',
cobrandPassword: 'yourpassword'
}
begin
response = site["/authenticate/coblogin"].post login_hash, :'content-type' => 'application/x-www-form-urlencoded'
puts response
rescue RestClient::ResourceNotFound => ex
raise Exception.new(ex.response)
rescue Exception => ex
raise Exception.new(ex)
end
end
def self.site_resource
RestClient::Resource.new('https://rest.developer.yodlee.com/services/srest/restserver/v1.0')
end
end
Yodlee.login_to_yodlee
Generally, this error comes when you do not provide the input parameter's name correctly; while in this mentioned code above I could see that both of them are correct. I'd suggest you to please double check the input parameter name(case sensitive) as well properly. And just to mention you should be sending it as two different parameters i.e., 'cobrandLogin' and cobrandPassword.

tastypie post authentication issues

I'm having trouble with tastypie and posting data to it. I only am able to retrieve a 401 error code.
For clarification, I am able to successfully retrieve data from the tastypie api.
Attached are the code snippets, and maybe someone can help me out get behind this.
Before I get started, a little background: I am using a custom authorization class.
class CustomAuthorization(Authorization):
def is_authorized(self, request, object=None):
if request.user.username == 'custom_user':
return True
return False
Here is the actual resource:
class CustomObjectResource(ModelResource):
class Meta:
queryset = CustomObject.objects.all()
authentication = ApiKeyAuthentication()
authorization = CustomAuthorization()
list_allowed_methods = ['get', 'post', ]
detail_allowed_methods = ['get', 'post', 'put']
include_resource_uri = False
resource_name = 'customobject'
always_return_data = True
def obj_create(self, bundle, request=None, **kwargs):
try:
print "request"
except:
raise BadRequest('I couldnt save your information.')
return True
I know the obj_create method is bogus, but it should still be called and do something, or is this already the issue?
The following curl command is used to post the data to the tastypie API.
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"body": "This will prbbly be my lst post.", "pub_date": "2011-05-22T00:46:38", "slug": "another-post", "title": "Another Post"}' http://local.com:8000/api/v1/customobject/?format=json&username=custom_user&api_key=123456789012345
The api_key is correct, but bogus in this case!
As previously mentioned, the get method works but the post just wont work.
Anyone have an idea on how to solve this or have a workaround?
I would try a couple of things to debug this issue.
1) Try adding: allowed_methods = ['get', 'post', 'put']
2) Add print statements in the custom_authorization to check if that is causing the problems due to the request.user.username being different.
3) Do (2) in the source of APIKeyAuthentication too.
This should be sufficient for you to debug the issue.
Remember to remove the print statements once youre done!
Best of luck.
This is COULD be due to a known issue. On the background tastypie at the moment converts the POST to PUT and as Nikunj pointed since in list_allowed_methods you don't have PUT the POST gets blocked too... Not sure there though cause you should get method not allowed in that case. I would suggest debug in the method "is_authorized" and check what is happening there.