Python3 Request from API return Not Found - python-3.x

I am trying to get a balance from some address at a explorer on Python but I get 404 error and I believe that is related to a list.
This is my code:
import urllib.request, json, requests
listAddress = [
"HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf"
]
explorerUrl = 'http://explorer.htmlcoin.com'
urlBase = '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/'
balance = '/balance'
for address in listAddress:
urlGamb = explorerUrl+urlBase+address+balance
json_data = urlGamb
r = requests.post(json_data)
r.status_code
r.json()
print(r.json())
The problem is that returns this error:
python3 newwork.py
{'status': 404, 'url': '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance', 'error': 'Not found'}
So, what am I doing wrong here?

Minor suggestion:
urlGamb = f"{explorerUrl}{urlBase}{address}{balance}"
I don't know about the API, you did not provide a link, but the value of urlGamb is 'http://explorer.htmlcoin.com/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance' and that is not JSON. The assignment to json_data seems like a conceptual error because the URL string is not json. If the post requires a JSON payload then the docs should tell you how to construct it.
Should the post have been a get request instead? That would make sense because according to REST standards, post is for changing state on the server, and you are only making a query.

Related

Rest API data reading present in swagger url using python library

I am trying to access swagger url that gives response upon sending request in json format. I have disabled to avoid SSLCertVerificationError using verify=False. How to access that please help me to read it using python code. You can get details what I have tried till now.
Installed requests library by using cmd in windows = pip install requests
I am able to get the 200 response by using code mentioned
When I am trying to use "params= payload" where. I am not able to get the response the same I am getting in the swagger url.
url : https:///#!/prepaid-estimate-controller/getAccountDetailsUsingPOST
payload={'searchCriteria': 'string', 'value': 'string'}
r4 = requests.get('https://<domain>/#!/prepaid-estimate-controller/getAccountDetailsUsingPOST', verify=False)
print(r4)
Output : 200
payload={'searchCriteria': 'string', 'value': 'string'}
r4 = requests.get('https://<domain>/#!/prepaid-estimate-controller/getAccountDetailsUsingPOST',params=payload, verify=False)
print(r4)
print(r4.text)
Output: DOM structure returns
This issue has been fixed by using below code generated in the postman.
import requests
url = "https:///bsi/prepaid/getAccountDetails"
payload = "{ \r\n "searchCriteria": "BAID", \r\n "value": "PPB006788"\r\n}"
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload, verify=False)
print(response.text.encode('utf8'))

How to get a POST request using python on HERE route matching API?

I've tried to do a POST request using python's request library, which looked something like below:
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url,data='Datasets/rtHereTest.csv')
The response I've been getting a code 400
{'faultCode': '16a6f70f-1fa3-4b57-9ef3-a0a440f8a42e',
'responseCode': '400 Bad Request',
'message': 'Column LATITUDE missing'}
However, in my dataset, here I have all the headings that's required from the HERE API documentation to be able to make a call.
Is there something I'm doing wrong, I don't quite understand the POST call or the requirement as the HERE documentation doesn't explicitly give many examples.
The data field of your post request should contain the actual data, not just a filename. Try loading the file first:
f = open('Datasets/rtHereTest.csv', 'r')
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url, data=f.read())
f.close()
Here's what I use in my own code, with the coordinates defined before:
query = 'https://rme.api.here.com/2/matchroute.json?routemode=car&app_id={id}&app_code={code}'.format(id=app_id, code=app_code)
coord_strings = ['{:.5f},{:.5f}'.format(coord[0], coord[1]) for coord in coords]
data = 'latitude,longitude\n' + '\n'.join(coord_strings)
result = requests.post(query, data=data)
You can try to post the data using below format.
import requests
url = "https://rme.api.here.com/2/matchroute.json"
querystring = {"routemode":"car","app_id":"{app_id}","app_code":"{app_code}","filetype":"CSV"}
data=open('path of CSV file','r')
headers = {'Content-Type': "Content-Type: text/csv;charset=utf-8",
'Accept-Encoding': "gzip, deflate",
}
response = requests.request("POST", url, data=data.read().encode('utf-8'), params=querystring,headers=headers)
print(response.status_code)

How to get the result from API not only the response code

I am trying to get the result of foreign currency exchange rate but on sending a Get request to the API "https://data.fixer.io/api/".." instead of getting a result, I am getting a response code 200 but no exchange rates are there
def main():
res=requests.get("http://data.fixer.io/api/latest? access_key = YOUR_ACCESS_KEY& base = INR& symbols = USD")
if res.status_code!=200:
raise Exception("Error : APIdidn't work")
print(res)
Expected result:
{
"success":true,
"timestamp":1559223544,
"base":"INR",
"rates":{
"USD":0.014,
}
}
Actual result :
<Response [200]>
To use the data that you're pulling from the API - you need to convert it to readable json. DeepSpace is correct - you need to use res.json()
Append the data to a variable if you want to iterate through it or utilize it further.
data = res.json()

Posting data on Airtable API does not work

I am trying to create a new table on Airtable with the aid of the post method. I have the following code :
# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "https://api.airtable.com/v0/appa3r2UUo4JxpjSv/Table%201?api_key=MYKEY"
# data to be sent to api
data = {
'fields': {
'Name': 'Andromachis Row'
}
}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
print(r.text)
Despite that when I run the script I get an error saying:
(mypyth) PS C:\Users\andri\PythonProjects\mypyth> py post_API.py
{"error":{"type":"INVALID_REQUEST_UNKNOWN","message":"Invalid request: parameter validation failed. Check your request data."}}
Does anyone understand why this happens? I am really desperate! Thanks in advance

Trying to use Yelp API for something other than business_id

I'm a student and only a few weeks into Python, so bear with me. I found a good answer in this link for initially working with Yelp's v3 API to at least get it to successfully make a request by business_id: How to use Yelp's new API
However, I can't seem to figure out how to search by anything other than reviews using the code that someone provided above (copy-pasted here as the below does work, just not what I need it for:
import requests
import yelp
from config import api_key
API_KEY = api_key
API_HOST = 'https://api.yelp.com'
BUSINESS_PATH = '/v3/businesses/'
def get_business(business_id):
business_path = BUSINESS_PATH + business_id
url = API_HOST + business_path + '/reviews'
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
results = get_business('the-white-horse-pub-kansas-city')
pprint(results)
Again, the code does work if you're only looking up one place by name. But when I try something other than "/reviews" in the url function, such as "search" or "term" or something else going off of the Yelp Fusion API documentation (https://yelp.com/developers/documentation/v3/business_search), I can't get anything to pull. My intent is to pull a bunch of breweries in the local area and then eventually put them in a dataframe, but I can't figure out what parameters or code to use, other than 'review'.
I believe I found an answer where you can at least look for type if you add the first item to the dependencies and the lower items as a separate function:
BUSINESS_PATH_CAT = '/v3/categories/'
def get_all_categories(alias):
url = API_HOST + BUSINESS_PATH_CAT + alias
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
results = get_all_categories('brewpubs')
pprint(results)
Aside from this though, on the authentication guide for Yelp Fusion, it discusses using Postman. If you're a fellow noob, setting this up can be a lifesaver as this allowed me to actually see the HTTP wording and how it's split up for search terms and how to add them compared to the API documentation.

Resources