Getting Request method 'GET' not supported - Python - python

So I've been trying to request an API using the following endpoint:
http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687*****
Using the following python code:
import requests
import json
resp_1 = requests.get("http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687*****")
res = resp_1.json()
print(res)
But I keep getting a Request method 'GET' not supported error even when I try the request directly from the browser.
I've been looking at the documentation for a while now and it's says that It's supposed to be a POST request.
Here: https://docs.viator.com/partner-api/affiliate/technical/#tag/Product-services/paths/~1search~1products/post
Any ideas on why this is happening and how to fix this?
UPDATE
Here's the new code I'm about to try:
import requests
import json
j="""{"destId": 684,"seoId": null,"catId": 3,"subCatId": 5318,"startDate": "2018-10-21","endDate": "2019-10-21","dealsOnly": false,"currencyCode": "EUR","topX": "1-3","sortOrder": "TOP_SELLERS"}"""
resp_1 = requests.post("http://viatorapi.viator.com/service/search/products?apiKey=98765687*****", data=json.loads(j))
res = resp_1.json()
print(res)

According to the documentation you linked,
it is clear that it only takes POST requests for /search/products. Generate a json (like the sample json from the documentation) and do a post request.
import requests
import json
j="""{
"destId": 684,
"seoId": null,
"catId": 3,
"subCatId": 5318,
"startDate": "2018-10-21",
"endDate": "2019-10-21",
"dealsOnly": false,
"currencyCode": "EUR",
"topX": "1-3",
"sortOrder": "TOP_SELLERS"
}"""
headers={'Content-type':'application/json', 'Accept':'application/json'}
resp_1 = requests.post("http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687*****", data=j, headers=headers)
print(resp_1.json())

Related

Trying to sort in an API

im new in this of "Calling APIs", so i don't understand a lot, I was wondering if anyone can help me.
I want to sort the cryptocurrencies from coinmarketcap whit their API, in the Api documentation, says that there is a parameter 'sort', and i can use differents values, like 'name','symbol' and 'recently added'. So if i want to get the last cryptocurrency listed, i have to sort whit 'recently added'. But i dont know how to do it. Here is a piece of code that i can write, but whit that code i get All the cryptocurrencys and i dont know how to sort it. Thanks
import requests
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
parameters = {
'start':'1',
'limit':'5000',
'convert':'USD'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'private key',
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
print(response.json())
I guess its
parameters = {
'start':'1',
'limit':'5000',
'convert':'USD',
'sort':'recently_added'
}
assuming you interpretted the docs right
it actually looks like it want 'sort':'date_added' NOT 'recently_added' based on the docs at https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest

Error when executing a python requests post script

I'm not sure what i'm doing wrong with the script below, but i keep getting this error when i try to execute the script. any idea what i'm doing wrong? thanks!
import requests
blxr_endpoint = "https://bxgw-nd-061-866-537.p2pify.com"
authorization = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
blxr_request_json = {
"method": "blxr_tx",
"params": {
"transaction": signed_txn.rawTransaction.hex()[2:],
}
}
result = requests.post(blxr_endpoint,json = blxr_request_json,auth = authorization)
Less familiar with the auth param , but from requests docs the auth param doesn't get string as an input.
It supposed to get a class that inherits from requests.auth.AuthBase like:
HTTPBasicAuth
HTTPDigestAuth
OAuth1
and other(you can also create one yourself.)
Another option is to insert the Authorization header of the http manually:
result = requests.post(blxr_endpoint, headers={'Authorization': authorization})

Understanding and Interacting with API using Python

I have a basic API installed as my localhost server that does functions such as add camera, star camera, list cameras, snapshot of camera frame, etc.
My problem is after following the documentation I still can't seem to interact with it well and get the response I need. Here is the code I use to log in and get validation token:
import requests
import urllib.request
import json
base_url = "http://localhostip:8080/api/user/login?"
parameters = {
"username": username,
"password": password
}
auth_tok = requests.post(base_url + urllib.parse.urlencode(parameters)).json()
print(auth_tok)
I get the correct documented response with a token, so following the documentation to add camera I need 2 parameters, URL and Name, so I did:
base_url = "http://localhostip:8080/api/camera/add?"
parameters = {
"url": 'rtsp://192.168.1.23/1',
#or video file
"url" : '/home/video/sample.mov'
"name" : 'cam1'
}
r = requests.post(base_url + urllib.parse.urlencode(parameters),headers={'Authorization': auth_tok})
when I print the response:
-print (r)
-print (r.url)
-print(r.status_code)
-print(r.json())
I get this:
<Response [500]>
http://192.168.0.162:8080/service/api/camera/add?url=rtsp%3A%2F%2Frtsp%3A%2F%2F192.168.1.23&name=cam1
500
{'code': -111, 'message': None}
According to documentation the correct url should be like this:
http://192.168.0.6:8080/service/api/camera/add?url=rtsp://192.168.1.23&name=cam1
and the response should be:
Response:
{"status":"ok"}
So why and how to make the URL POST in the correct format, because I suspect this is the issue, the URL has these encoding symbols that may be messing up the request?
When I use the web browser GUI of this API I can add the camera or even a video file to play but I'm trying to do the same with Python so I can do further processing in future.
Your problem is when you encode the ' / / ' symbol, so, in order to fix that, you need to use another function from urllib, urllib.parse.unquote(), and use as parameter your encoding function urllib.parse.urlencode(parameters):
import urllib
parameters = {
"url": 'rtsp://192.168.1.23/1',
"name" : 'cam1'
}
The results are :
print(urllib.parse.urlencode(parameters))
'url=rtsp%3A%2F%2F192.168.1.23%2F1&name=cam1'
print(urllib.parse.unquote(urllib.parse.urlencode(parameters)))
'url=rtsp://192.168.1.23/1&name=cam1'
Source https://docs.python.org/3.0/library/urllib.parse.html#urllib.parse.unquote

Get access token for google by using Python requests library

Trying to get the access token in response for google but can't figure out what I'm doing wrong.
This is what I've done so far:
import requests
authorization_code_req = {
'client_id':'key',
'client_secret':'key',
'redirect_uri':'http://localhost:5000',
'grant_type':'authorization_code'}
r = requests.get('https://accounts.google.com/o/oauth2/token',
params=authorization_code_req)
print (r)
you should send authorization_code_req as json and not as params. So your code should look something like this:
import requests
authorization_code_req = {
'client_id':'key',
'client_secret':'key',
'redirect_uri':'http://localhost:5000',
'grant_type':'authorization_code'
}
r = requests.get('https://accounts.google.com/o/oauth2/token',
json=authorization_code_req)
print(r)

Python 3 Get HTTP page

How can I get python to get the contents of an HTTP page? So far all I have is the request and I have imported http.client.
Using urllib.request is probably the easiest way to do this:
import urllib.request
f = urllib.request.urlopen("http://stackoverflow.com")
print(f.read())
Usage built-in module "http.client"
import http.client
connection = http.client.HTTPSConnection("api.bitbucket.org", timeout=2)
connection.request('GET', '/2.0/repositories')
response = connection.getresponse()
print('{} {} - a response on a GET request by using "http.client"'.format(response.status, response.reason))
content = response.read().decode('utf-8')
print(content[:100], '...')
Result:
200 OK - a response on a GET request by using "http.client"
{"pagelen": 10, "values": [{"scm": "hg", "website": "", "has_wiki":
true, "name": "tweakmsg", "links ...
Usage third-party library "requests"
response = requests.get("https://api.bitbucket.org/2.0/repositories")
print('{} {} - a response on a GET request by using "requests"'.format(response.status_code, response.reason))
content = response.content.decode('utf-8')
print(content[:100], '...')
Result:
200 OK - a response on a GET request by using "requests"
{"pagelen": 10, "values": [{"scm": "hg", "website": "", "has_wiki":
true, "name": "tweakmsg", "links ...
Usage built-in module "urllib.request"
response = urllib.request.urlopen("https://api.bitbucket.org/2.0/repositories")
print('{} {} - a response on a GET request by using "urllib.request"'.format(response.status, response.reason))
content = response.read().decode('utf-8')
print(content[:100], '...')
Result:
200 OK - a response on a GET request by using "urllib.request"
{"pagelen": 10, "values": [{"scm": "hg", "website": "", "has_wiki":
true, "name": "tweakmsg", "links ...
Notes:
Python 3.4
Result from the responses most likely will be differ only content
You can also use the requests library. I found this particularly useful because it was easier to retrieve and display the HTTP header.
import requests
source = 'http://www.pythonlearn.com/code/intro-short.txt'
r = requests.get(source)
print('Display actual page\n')
for line in r:
print (line.strip())
print('\nDisplay all headers\n')
print(r.headers)
pip install requests
import requests
r = requests.get('https://api.spotify.com/v1/search?type=artist&q=beyonce')
r.json()
Add this code which can format data for human reading:
text = f.read().decode('utf-8')
https://stackoverflow.com/a/41862742/8501970
Check this out instead. Its about the same issue you have and this one is very simple and very few lines of codes.
This sure helped me when i realized python3 cannot use simply get_page.
This is a fine alternative.
(hope this helps, cheers!)

Categories