I wrote the following code to find all molecules in PubChem which have an ExactMass of, in this case, 1176.784 +/- 0.01 Da. I get an error request fail [code 400]. The url should be ok, I checked the PubChem documentation, however I can't find the problem.
import requests
exact_mass = 1176.784 # set the exact mass value
tolerance = 0.01 # set the tolerance value
# set the API endpoint URL
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/list/exactmass/%f+-%0.3f/property/IUPACName/JSON" % (exact_mass, tolerance / 2)
# make the API request and retrieve the response
response = requests.get(url)
# check if the request was successful
if response.ok:
# extract the JSON data from the response
json_data = response.json()
# extract the list of compounds from the JSON data
compound_list = json_data['IdentifierList']['CID']
# print the IUPAC names of the compounds in the list
for cid in compound_list:
# set the API endpoint URL to retrieve IUPAC name for a specific CID
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%d/property/IUPACName/JSON' % cid
response = requests.get(url)
json_data = response.json()
iupac_name = json_data['PropertyTable']['Properties'][0]['IUPACName']
print(iupac_name)
else:
# print an error message if the request failed
print('Error: Request failed with status code %d' % response.status_code)
I expect to get a list of names of all molecules which have an ExactMass which is in the range of 1176.784 +/- 0.01 Da.