I have been on this site and cannot find a suitable resolution to this problem.
I can connect to my system via Powershell using the following;
$auth = '{"username":' + '"' + $user + '","password":' + '"' + $Pass + '"}'
$body = $auth
$hdrs = #{}
$hdrs.Add("X-API-KEY", "???")
$r = Invoke-RestMethod -Uri http://$URLSystem/login -Method Post -Body $body -ContentType 'application/json' -Headers $hdrs
I get a response back of 200 and I can get session keys etc...
I have tried a number of things in Python to connect to the same system. I tried this basic approach;
import requests
from requests.auth import HTTPBasicAuth
basic = HTTPBasicAuth('user1','pass1')
r = requests.get("http://URLSystem/login", auth=basic)
print(r.headers)
print(r)
I get a 405 response code. I have tried changing the get to a POST and get a 415 error response.
I am new to Python and having a little difficulty getting this going. Any help would be greatly appreciated.
Thank you for the response.
I will look at the resources you pointed out - this was helpful.
Yes, I thought I should be using request.post(...) but could not get the right format for headers and params to use.
I did find this post #this web site and it worked for me with some slight modification, so I am good for now...
Posting the solution here for anyone else if they have similar issues.
import requests
import json
URL = 'http://your-url'
headers = {
"accept": "application/json",
"Content-Type": "application/json"
}
params = {
"username": "yourusername",
"password": "yourpassword"
}
resp = requests.post(URL, headers = headers ,data=json.dumps(params))
session = json.loads(resp.text)['SessionToken']
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Response Code: ' + str(resp.status_code) + ', Session-Token: ' + str(session))
Related
I'm trying to get a token using Spotify's Client Credentials Flow and Python, however I just get the following:
{"error":"invalid_client","error_description":"Invalid client"}
I'm following this guide - https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/
Using this example script as a starting point - https://www.w3schools.com/python/showpython.asp?filename=demo_requests_post_headers
Here's my code (I've changed the Base 64 encoded string that contains the client ID and client secret key):
import requests
url = 'https://accounts.spotify.com/api/token'
myobj = {'grant_type': 'client_credentials'}
#use the 'headers' parameter to set the HTTP headers:
x = requests.post(url, data = myobj, headers = {"Authorization": "Basic Base64EncodedStringHere==","Content-Type": "application/x-www-form-urlencoded"})
print(x.text)
If I change the last line to print(x), I just get: <Response [400]>
Clearly I'm doing something wrong, but I can't figure out what?
I had the same problem while following a tutorial but I manage to find a solution on the Spotify community.
import requests
import base64
client_id = "your client id here"
client_secret = "your client secret here"
encoded = base64.b64encode((client_id + ":" + client_secret).encode("ascii")).decode("ascii")
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + encoded
}
payload = {
"grant_type": "client_credentials"
}
response = requests.post("https://accounts.spotify.com/api/token", data=payload, headers=headers)
print(response.text)
I am following a simple example (or what I thought was simple) of creating a python script that used the REST api to connect to wordpress.
However, I am getting a 403 error. My credentials are correct because I can log in with them.
I have been working over this for awhile now. Can anyone see where my error might be? Thank you.
url = "https://prod-wp.xxxxxx.com/wp-json/wp/v2/posts"
user = "xxxxxx"
password = "xxxxxxxx"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
response = requests.get(url , headers=header)
print(response)
<Response [403]>
EDIT
I have changed the code and this seems to work.
import requests
import os
from dotenv import load_dotenv
load_dotenv()
BASE_URL = 'https://website.com/wp-json'
WP_URL = os.getenv("WP_URL")
WP_USERNAME = os.getenv("WP_USERNAME")
WP_PASSWORD = os.getenv("WP_PASSWORD")
def get_headers():
wp_credentials = {'username': WP_USERNAME, 'password': WP_PASSWORD}
jwt_response = requests.post(f'{BASE_URL}/jwt-auth/v1/token', json=wp_credentials)
jwt_token = jwt_response.json()['token']
headers = {
"Authorization": "Bearer %s" % jwt_token,
"Content-Type": "application/json",
"Accept": "application/json",
}
print(f'Headers are equal to: {headers}')
return headers
get_headers()
I was able to get the auth token from the login api but I am trying to use it to query the events api and I am getting a 401 Client Error: Unauthorized for url error message. Here is a snippet of my code:
def action():
data = {
'login': 'xxxxxxxxx',
'password': 'xxxxx',
}
urllib3.disable_warnings()
try:
timestamp = int(round(time.time() * 1000))
print(timestamp)
r = requests.post(
'https://host:port/www/core-service/rest/LoginService/login', data=data, verify=False)
login_request = untangle.parse(r.text)
user_session_id = login_request.ns3_loginResponse.ns3_return.cdata
print(user_session_id)
response = requests.post(
'https://host:port/detect-api/rest/v1/events/retrieve',
headers={
"Accept": "application/json",
"Authorization": user_session_id,
"Content-Type": "application/json"
},
data={
"ids": 79745681,
"startTime": timestamp,
"endTime": timestamp
},
verify=False)
print(response)
res = untangle.parse(response.text)
print(res)
Can somebody please point out what is wrong with my code?
You didn't add link to API so I only guess what can make problem.
If you set "Content-Type": "application/json" then it can means you want to send json data.
So you should use
post(..., json=...)
instead of
post(..., data=...).
Using data= you send it as form, not json. And header Content-Type can't change it.
And when you use json= then you don't have to add "Content-Type": "application/json" because requests will add it automatically.
EDIT:
In comment you said that you have working curl command (but you didn't said it in question, and you didn't show curl in question)
On page https://curl.trillworks.com you can convert curl to Python (and few other languages) and mostly it works correctly.
BTW:
If you use postman for tests then it has also function to generate code for curl, Python and many other languages.
You didn't show link to API documentation but often API documentation has examples for curl and sometimes even for Python.
i'm working on settin up a rest api with python, however i'm having some problem getting it to work.
I'm working with the TV DB rest api: https://api.thetvdb.com/swagger
and using python with Requests library to pull out the information.
My code is currently:
import json
import requests
URL = "https://api.thetvdb.com/"
API_KEY = "Api_key"
USER_KEY = "Key"
USERNAME = "Name"
headers = {"Accept": "application/json"}
params = {
"apikey": API_KEY,
"userkey": USER_KEY,
"username": USERNAME
}
resp = requests.post(URL + "login/", headers = headers ,params=params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
So far i'm only getting error code 401, not sure why.
Solved:
2 Things needed to be changed
1. The resp was changed into:
resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
The header had to have
"Content-Type": "application/json"
added to it :) It's now working, thanks everyone
The login parameters probably need to be a JSON-encoded string POSTed as the body of the message.
Try resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
I'm at the first stage of integrating our web app with PayPal's express checkout api. For me to place a purchase, I have to get a Bearer token of course using our client id and our client secret.
I use the following curl command to successfully get that token:
curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "ourID:ourSecret" \
-d "grant_type=client_credentials"
Now I am trying to achieve the same results in python using urllib2. I've arrived at the following code, which produces a 401 HTTP Unauthorized exception.
import urllib
import urllib2
url = "https://api.sandbox.paypal.com/v1/oauth2/token"
PAYPAL_CLIENT_ID = "ourID"
PAYPAL_CLIENT_SECRET = "ourSecret"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
req = urllib2.Request( url=url,
headers={
"Accept": "application/json",
"Accept-Language": "en_US",
},
data =urllib.urlencode({
"grant_type":"client_credentials",
}),)
result = urllib2.urlopen(req).read()
print result
Does anyone have any idea what I'm doing wrong above? Many thanks for any insights
Experiencing the same problem here. Based on Get access token from Paypal in Python - Using urllib2 or requests library working python code is:
import urllib
import urllib2
import base64
token_url = 'https://api.sandbox.paypal.com/v1/oauth2/token'
client_id = '.....'
client_secret = '....'
credentials = "%s:%s" % (client_id, client_secret)
encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
header_params = {
"Authorization": ("Basic %s" % encode_credential),
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
param = {
'grant_type': 'client_credentials',
}
data = urllib.urlencode(param)
request = urllib2.Request(token_url, data, header_params)
response = urllib2.urlopen(request).open()
print response
The reason, I believe, is explained at Python urllib2 Basic Auth Problem
Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the servers don't do "totally standard authentication" then the libraries won't work.