How to resolve 400 Client Error when mapping uniprot IDs programatically? - python-3.x

Here's the code:
API_URL = "https://rest.uniprot.org"
def submit_id_mapping(from_db, to_db, ids):
request = requests.get(
f"{API_URL}/idmapping/run",
data={"from": from_db, "to": to_db, "ids": ",".join(ids)},
)
#request.raise_for_status()
return request.json()
submit_id_mapping(from_db="UniProtKB_AC-ID", to_db="ChEMBL", ids=["P05067", "P12345"])
Taken directly from the official example
And returning the following 404 client error. I tried accessing the url myself and it doesn't seem to work. Given that this is the official documentation I don't really know what to do. Any suggestions are welcomed.
{'url': 'http://rest.uniprot.org/idmapping/run',
'messages': ['Internal server error']}
I also have another script for this but it no longer works! And I don't know why :(
in_f = open("filename")
url = 'https://www.uniprot.org/uploadlists/'
ids=in_f.read().splitlines()
ids_s=" ".join(ids)
params = {
'from': 'PDB_ID',
'to': 'ACC',
'format': 'tab',
'query': ids_s
}
data = urllib.parse.urlencode(params)
data = data.encode('utf-8')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as f:
response = f.read()
print(response.decode('utf-8'))
Error:
urllib.error.HTTPError: HTTP Error 405: Not Allowed

Try to change .get to .post:
import requests
API_URL = "https://rest.uniprot.org"
def submit_id_mapping(from_db, to_db, ids):
data = {"from": from_db, "to": to_db, "ids": ids}
request = requests.post(f"{API_URL}/idmapping/run", data=data)
return request.json()
result = submit_id_mapping(
from_db="UniProtKB_AC-ID", to_db="ChEMBL", ids=["P05067", "P12345"]
)
print(result)
Prints:
{'jobId': 'da05fa39cf0fc3fb3ea1c4718ba094b8ddb64461'}

Related

Python requests session post to aiohttp session post

I have a synchronous code with requests that I am trying to move to using aiohttp.ClientSession.
Indeed, I have a class in which I set a aiohttp.ClientSession with various headers, among those an API key. The above code works for requesting data: (I deleted the init.... everything works but this function)
class Client():
def __init__(self):
loop = asyncio.get_event_loop()
self.session = aiohttp.ClientSession(
loop=loop,
headers=self.get_headers()
)
def send_signed_request(self, url_path, payload={}):
session = requests.session()
session.headers.update(self._get_headers())
query_string = urlencode(payload)
url = url_path + '?' + query_string
params = {'url': url, 'params': {}}
response = session.post(**params)
return response.json()
client = Client()
results = client.send_signed_request(url, params)
From that, with the requests session, I obtain a valid response from the server.
for some reason, the code below, with aiohttp session does not work and I have no idea how to adapt it.
async def send_signed_request(self, url_path, payload={}):
query_string = urlencode(payload)
url = url_path + '?' + query_string
params = {'url': url, 'data': {}}
async with self.session.post(**params) as response:
return await response.json()
does anybody knows my error please?

<Response [500]> while POST request

Trying to get information with post request but it returns RESPONSE [500]. I have tried to use the get response and it returns response 200 code. I copied the form_data from the website and included in my code.
import requests, json
from bs4 import BeautifulSoup as bs
from requests.utils import quote
url = 'https://mpcr.cbar.az/service/mpcr.publicSearchApplication'
tax_ids = [
'1000276532',
]
data = {
'searchFilter': {"fields":"{\"orgTin\":\"%s\"}"},
'compId': 'frontend',
'access_token': '123',
'refresh_token': '123',
'token': '123',
'requestNumber': '1p5i9m5s9T9W8',
'_token': 'MQ2cZyD092qFKknKpZMV0w2ksNhqWj17PSl6iaCG',
}
with requests.Session() as s:
for i in tax_ids:
data["searchFilter"] = quote(json.dumps(data["searchFilter"]["fields"] % i))
print(data)
print("--" * 10)
r = s.post(url, data=data)
print(r)

How to send POST request after form submit 302 in Django?

I have an implementation as follows:
There is a payment form wherein user fills all the details.(API1), here I'm getting an error 302:
On submit of that form one of the function in my views is called.
In the backend implementation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)
But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request.
Following is the code.
views.py -->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
content = response.url
return_config = {
"type": "content",
"content": redirect(content)
}
return return_config
How do I send the 2nd request(API2) as POST request along with all parameters? What am I doing wrong here?
Thank you for your suggestions.
If the requests returns a 302 status, the new url is available in response.headers['Location']. You can keep following the new url, till you end up with a valid response.
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
while response.status_code == 302:
response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)
content = response.text
return_config = {
"type": "content",
"content": content
}
return return_config
# here you are assigning the post url to content ie. 'https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****'
content = response.url
return_config = {
"type": "content",
"content": redirect(content) # calling redirect with the response.url
}
change to:
# check status code for response
print(response)
content = response.json() # if response is of json in format
content = response.text # if response is of plain text
return_config = {
"type": "content",
"content": content
}
return return_config
request.post() returns requests.Response object. inorder to get the response data you need to access it using .text or .json() depending on the format in which the response is sent.

python requests error check-mk API

I am trying to add dictionary data to our check-mk Web API wit Python requests, but I keep getting an Error of missing keys:
{"result": "Check_MK exception: Missing required key(s): aux_tags, tag_groups", "result_code": 1}
Here is my code:
import json
import requests
params_get = (
('action', 'get_hosttags'),
('_username', 'user'),
('_secret', 'secret'),
('request_format', 'json'),
)
params_set = (
('action', 'set_hosttags'),
('_username', 'user'),
('_secret', 'secret'),
('request_format', 'json'),
)
url = 'http://monitoringtest.local.domain/test/check_mk/webapi.py'
tags = ['tag1', 'tag2']
response_data = requests.get(url, params=params_get)
data = response_data.json()
new_data_tags = data['result']['tag_groups']
new_data = data['result']
# new_tags = []
for tag in tags:
new_data['aux_tags'].append({'id': tag, 'title': 'tags in datacenter'})
# new_tags.extend([{'aux_tags': [], 'id': tag, 'title': tag.upper() + ' Tag'}])
# all_tags = new_data_tags.extend([{'tags': new_tags, 'id': 'group1', 'title': 'tags in datacenter'}])
json.dump(data['result'], open("new_file", "w"))
response_data_new = requests.get(url, params=params_set, json=json.dumps(data['result']))
# response_data_new = requests.put(url, params=params_set)
# requests.post(url, params=params_set)
print(response_data_new.text)
# print(data['result'])
# json.dump(data['result'], open("new_file", "w"))
When I use curl every thing works well with a success message:
{"result": null, "result_code": 0}
Do you have any idea what causes the error?
Thanks
I found the mistake, it was just not focused. The Data variable contains two keys that are sent as well result at the beginning and result_code at the end, which need to be truncated. I just had to modify the response as follows, and sending the data wit POST:
resp = requests.post(url, params=params_set, data={'request': json.dumps(data['result'])})
Thanks #DeepSpace

Get Survey Response Survey Monkey (Python)

Im quite new to http request. Im having abit of troubleshooting trying to get survey results/responses from survey monkey api 3.
Here is the following code i have:
import requests
import json
client = requests.session()
headers = {
"Authorization": "bearer %s" % "VVZEO3u35o3JVDdd8z5Qhl-eRR5Er2igaV1gf8GS4dvRfYVk3SWu9nHginwyNnU.tAHEr-AtikR9Zpg7vL3-jIg3-6yuQkPBvVIw0AkpYN5807SCLIrGojsii3ihdGV-",
"Content-Type": "application/json"
}
data = {}
HOST = "https://api.surveymonkey.net"
#SURVEY_LIST_ENDPOINT = "/v3/surveys/%s/responses/%s/details" %("85160626","161")
SURVEY_LIST_ENDPOINT = "/v3/surveys/85160626/responses"
uri = "%s%s" % (HOST, SURVEY_LIST_ENDPOINT)
response = client.post(uri, headers=headers, data=json.dumps(data))
response_json = response.json()
#survey_list = response_json["data"]["surveys"]
print(response_json)
I keep getting error:
{'error': {'docs': 'https://developer.surveymonkey.com/api/v3/#error-codes', 'message': 'There was an error retrieving the requested resource.', 'id': '1020', 'name': 'Resource Not Found', 'http_status_code': 404}}
Any help is much appreciated, thanks,
Pon
If you're trying to fetch data, then you should be doing a GET request, not a post.
response = client.get(uri, headers=headers)
Otherwise it looks fine, just make sure the Survey ID is correct.

Resources