Error when executing a python requests post script - python

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})

Related

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

Getting Request method 'GET' not supported - 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())

how to add authorization headers to bravado-created API client

I am able to create a simple API interface using the requests module that authenticates correctly and receives a response from an API. However, when I attempt to use bravado, to create the client from a swagger file, and manually add an authorization token to the head, it fails with :
bravado.exception.HTTPUnauthorized: 401 Unauthorized: Error(code=u'invalid_credentials', message=u'Missing authorization header',
I believe I am adding the authorization headers correctly.
The code I'm using to create the client is below. As shown, I've tried to add an Authorization token two ways:
in the http_client setup via set_api_key
in the Swagger.from_url(...) step by adding request_headers.
However both options fail.
from bravado.requests_client import RequestsClient
from bravado.client import SwaggerClient
http_client = RequestsClient()
http_client.set_api_key(
'https://api.optimizely.com/v2', 'Bearer <TOKEN>',
param_name='Authorization', param_in='header'
)
headers = {
'Authorization': 'Bearer <TOKEN>',
}
client = SwaggerClient.from_url(
'https://api.optimizely.com/v2/swagger.json',
http_client=http_client,
request_headers=headers
)
My question is, how do I properly add authorization headers to a bravado SwaggerClient?
For reference, a possible solution is to add the _request_options with each request:
from bravado.client import SwaggerClient
headers = {
'Authorization': 'Bearer <YOUR_TOKEN>'
}
requestOptions = {
# === bravado config ===
'headers': headers,
}
client = SwaggerClient.from_url("<SWAGGER_JSON_URL>")
result = client.<ENTITY>.<ACTION>(_request_options=requestOptions).response().result
print(result)
However, a better solution, which I still am unable to get to work, is to have it automatically authenticate with each request.
Try again, fixing the host of the set_api_key line.
from bravado.requests_client import RequestsClient
from bravado.client import SwaggerClient
http_client = RequestsClient()
http_client.set_api_key(
'api.optimizely.com', 'Bearer <TOKEN>',
param_name='api_key', param_in='header'
)
client = SwaggerClient.from_url(
'https://api.optimizely.com/v2/swagger.json',
http_client=http_client,
)
Here you will find documentation about the method : https://github.com/Yelp/bravado/blob/master/README.rst#example-with-header-authentication

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)

Symantec End Point Manager API - Authentication issues

The following is my code:
import requests, json
proxyDict = {
"http": "<proxy>",
}
base_url = "https://<host_IP>/sepm/api/v1/identity/authenticate"
# if output is required in JSON format
json_format = True
payload = {
"username" : "<username_here>",
"password" : "<password_here>",
"domain" : ""
}
headers = {
"Content-Type" : "application/json"
}
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL' # necessary
r = requests.Session() # Start session in order to store the SessionID Cookie
print json.dumps(payload)
r = requests.post(base_url, proxies=proxyDict, verify=False, headers=headers, data=json.dumps(payload))
strings = r.text
print strings
The SSL certificate has some errors, and I am hence using verify=False and DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL'
The above code is inline with the documentation provided, but the server is refusing my auth request, with the following error:
{"errorCode":"400","errorMessage":"Invalid Username or Password"}
Before you jump the gun, I checked and rechecked my credentials, and then checked a couple of more times. my credentials are correct
Is there an error in what I am doing?
Additional info: SEPM Version: {"version":"12.1.6168.6000"}
Late to this party, but I was having the same issue with almost the although going about it a bit differently. SO, what my issue ended up being was the special characters in my password. The rest method that handles authentication on the Symantec manager side of things doesn't know how to handle certain special characters so it returns a 400 syntax error. Trying pulling special characters from you password, and keep it under 15 characters.
Good luck.
You might want to try putting the below line near the top of your code:
urllib3.disable_warnings()
And ignore the SSL authentication

Categories