I Call API from PYTHON I get the response 406 Not Acceptable

Question:

I created a API in my site and I’m trying to call an API from python but I always get 406 as a response, however, if I put the url in the browser with the parameters, I can see the correct answer

I already did some test in pages where you can tests you own API, I test it in the browser and work fine.
I already followed up a manual that explains how to call an API from python but I do not get the correct response 🙁

This is the URL of the API with the params:
https://icassy.com/api/login.php?usuario_email=warles34%40gmail.com&usuario_clave=123

This is the code I use to call the API from Python

import requests
urlLogin = "https://icassy.com/api/login.php"
params = {'usuario_email': '[email protected]', 'usuario_clave': '123'}
r = requests.get(url=urlLogin, data=params)
print(r)
print(r.content)

and I get:

<Response [406]>
b'<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>'

I should receive in JSON format the success message and the apikey like this:

{“message”:”Successful login.”,”apikey”:”eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2ljYXNzeS5jb20iLCJpYXQiOjEzNTY5OTk1MjQsIm5iZiI6MTM1NzAwMDAwMCwiZGF0YSI6eyJ1c3VhcmlvX2lkIjoiMzQiLCJ1c3VhcmlvX25vbWJyZSI6IkNhcmxvcyIsInVzdWFyaW9fYXBlbGxpZG8iOiJQZXJleiIsInVzdWFyaW9fZW1haWwiOiJ3YXJsZXMzNEBnbWFpbC5jb20ifX0.bOhrC-vXhQEHtbbZGmhLByCxvJY7YxDrLhVOfy9zeFc”}

Asked By: Samper

||

Answers:

Looks like there is a validation on the server to check if request is made from some browser. Adding a user-agent header should do it –

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.get(url=urlLogin, params=params, headers=headers)

This link of user agents might come handy in future.

Answered By: Sushant

I turned out that the service I was doing a request to was hosted on Akamai that has a bot manager. It looks at the requests (where it comes from) and if it determines that it is a bot you get a 406 error.

The solution was to ask for the server IP to be whitelisted, or to send a special header to all server communication.

In my case, I had

'Accept': 'text/plain'

and it worked after I replaced it with

'Accept': 'application/json'

I didn’t need to use user-agent at all

Answered By: Marvin Zumbado