error in finding Spotify user ID with python - python

hey im trying to fetch my spotify user ID in order to create a playlist on my profile
im able to find the songs im interested in using the spotify API but im stuck after that
this is my code to find user ID
`
# Use the Spotify API to get the authenticated user's ID
headers = {
'Authorization': 'Bearer ' + access_token
}
response = requests.get('https://api.spotify.com/v1/me', headers=headers)
if response.status_code == 200:
# Success!
user_id = response.json()['id']
else:
# Error occurred
print('Error:', response.status_code)
it keeps giving me a 401 error
after that im trying to create a playlist and add songs to that playlist
`
# Use the Spotify API to create a new playlist
headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json'
}
data = {
'name': 'Sample Playlist',
'public': True
}
response = requests.post('https://api.spotify.com/v1/me/playlists', headers=headers, json=data)
if response.status_code == 201:
# Success!
playlist_id = response.json()['id']
else:
# Error occurred
print('Error:', response.status_code)
``
please help
i tries using the endpoints in the docs but no solution

Related

how do i make a user join a guild automatically using discord API? (PYTHON REQUESTS)

Im new to using discords API,
The issue im having is with Oauth2's "Access_Token", im not sure how to get an access token to have the user join the guild automatically this is the full code i have so far (i followed a tutorial to the letter literally) and im not sure what to do, i've seen other bots use it for advertising and so on but i've not been able to figure it out..
import requests
API_ENDPOINT = 'https://discord.com/api/v8'
CLIENT_ID = 'ID'
CLIENT_SECRET = 'SECRET HERE'
REDIRECT_URI = "https://google.com"
def exchange_code(code):
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers)
r.raise_for_status()
return r.json()
def add_to_guild(access_token, userID, guildID):
url = f"{API_ENDPOINT}/guilds/{guildID}/members/{userID}"
botToken = "BOT TOKEN"
data = {
"access_token" : access_token,
}
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
response = requests.put(url=url, headers=headers, json=data)
print(response.text)
code = exchange_code('QxoDC6swoZVJd2Gd9NCgliHy2eznBg')['access_token']
add_to_guild(code, 'USERID', 'GUILDID')
i tried using some other code and going through the documentation which unhelpfully is in javascript so i have no clue what im doing right or what im doing wrong, the expected result was to see when the user clicks the oauth2 link it will ask them if they want to allow it to join guilds for you, if they accept then it joins the guild for them

401 Client Error: Unauthorized url. Flask python

I have a program that Authenticate with API and when logged in search by Id in contacts on this API.
logging in works fine but when I try to find contact this error happen:
401 Client Error: Unauthorized for url:https://api.moxiworks.com/api/contacts/12345678
and same problem happen when try it on Postman like in this image:
after log in I redirected to home route and here is the code:
#app.route('/home', methods=["GET", "POST"])
#login_required
def home():
if request.method == "POST":
found = request.form.get('id')
#base64 encoded Partner ID and Partner Secret
sample_string = ('%s:%s' % (os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"))).replace('\n', '')
sample_string_bytes = sample_string.encode("ascii")
base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")
if not found:
return render_template('apology', err='must provide id')
try:
token = session['token']
response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
token=token,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % base64_string,
'Accept': 'application/vnd.moxi-platform+json;version=1',
'Cookie': '_wms_svc_public_session'
})
if response.status_code == 429:
flash('too many requests, wait for 60 seconds then will get your results')
time.sleep(60)
response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
token=token,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % base64_string,
'Accept': 'application/vnd.moxi-platform+json;version=1',
'Cookie': '_wms_svc_public_session'
})
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError as err:
return render_template('apology.html', err=err)
except Exception as err:
return render_template('apology.html', err=err)
else:
try:
contact = response.json()
return render_template('data.html',
contact1=contact['agent_uuid'], contact2=contact['moxi_works_agent_id'],
contact3=contact['partner_contact_id'], contact4=contact['contact_name'],
contact5=contact['primary_email_address'], contact6=contact['secondary_email_address'],
contact7=contact['primary_phone_number'], contact8=contact['secondary_phone_number'])
except (KeyError, TypeError, ValueError) as err:
return render_template('apology.html', err=err)
else:
return render_template('home.html')
What I miss? or what is wrong in my code?
here is the auth register:
moxi = oauth.register(
name='moxi',
client_id=os.getenv("CLIENT_ID"),
client_secret=os.getenv("CLIENT_SECRET"),
access_token_url='https://sso.moxiworks.com/oauth/token',
access_token_params={'grant_type': 'authorization_code'},
authorize_url='https://sso.moxiworks.com/oauth/authorize',
authorize_params={'response_type': 'code'},
api_base_url='https://api.moxiworks.com/api/contacts/',
userinfo_endpoint='https://sso.moxiworks.com/agent/profile', # This is only needed if using openId to fetch user info
client_kwargs = {
'scope': 'profile',
'token_endpoint_auth_method': 'client_secret_basic',
'token_placement': 'header',
}
)
please help me to figure out how to fix this?
thanks in advance.
The error shows that you have not included your authorisation header. According to the Basic Authentication standard (RFC 7617) used here, you should include the access token in the Authorization header instead of the parameter. As such, it should look something like this enter image description here.
Or on the python code, it will look like this
import requests
url = "https://example.com/api/contacts/1234"
payload = {}
headers = {'Authorization': 'Basic <access_token>'}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)

getting “Only valid bearer authentication supported” when searching for artist info

I am trying to get artist information using the Spotify API. Authorization key works with Spotify console. but when I am running my python file in my machine it showing error only valid bearer authentication supported.
import requests
import json
import pprint
endpoint_url = "https://api.spotify.com/v1/search?"
# OUR FILTERS
query = "john"
typ = "artist"
limit = 1
offset = 1
token="BQCjNYC2q_m1e_JAQgttZ3F-1CW1mnai9E2psfLbwY15kbtd7u2sjuPiF7ld8hbUshPJGLlBK3kLDIebgtk_K3bDrggExZDJ1zEMb8WVvV1DEx2rUK2youoeqT1rmXDT99P04rs8O0ie"
query = f'{endpoint_url}q={query}&type={typ}&limit={limit}&offset={offset}'
response = requests.get(query,
headers={"Content-Type": "application/json",
"Authorization": token})
json_response = response.json()
pprint.pprint(json_response)
Result:
{'error': {'message': 'Only valid bearer authentication supported',
'status': 400}}
You need to append 'Bearer' to the value of the Authorization header:
"Authorization": 'Bearer ' + token
edit:
As you are using Python 3.6 or further:
"Authorization": f'Bearer {token}'

Basic Authentication returns 401 Client Error but works in postman

I have gone through number of similar posts related to firing GET requests with Basic Auth (eg: Python, HTTPS GET with basic authentication), still can't figure out the problem. I keep getting the error requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url
With the same credentials, headers tried the same in postman it works as expected. Verified that base64encoded value for the api_key, password is exactly same as the value used in postman, so I don't think its encoding or resource access permission problem.
python -V
Python 3.6.4 :: Anaconda, Inc.
Approach 1
api_key = 'some_api_key'
password = 'some_password'
headers = {'accept': 'application/json'}
url = 'https://test.access.com/this/url'
api_key_password = "%s:%s" % (api_key, password)
b64_encoded = b64encode(bytes(api_key_password, 'utf-8')).decode("ascii")
headers['authorization'] = 'Basic %s' % b64_encoded
response = requests.get(url,
headers=headers)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
Approach 2
api_key = 'some_api_key'
password = 'some_password'
url = 'https://test.access.com/this/url'
headers = {
'accept': 'application/json',
}
response = requests.get(url, headers=headers, auth=(api_key, password))
print (response.ok)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
Can you please provide some pointers?
I had a similar issue (although in .NET Framework).
In my case the reason was that I was using the url without a forward slash in the end and the API apparently does not support that.
So https://test.access.com/this/url
Throws 401 error Unauthorized
but
https://test.access.com/this/url/
Returns 200 OK.
Older post but I had a similar issue. Postman will cache your JSESSIONID. Be sure you are clearing out that cookie while testing. If you are hitting an API that requires a login API call to establish a session before you can make subsequent API calls, this Postman behavior can produce a false sense of security.
In this situation with Python requests, it can be handled with code similar to what I've provided below:
import requests,json
loginAPI = "https://myapi.myco.comv/someuri/someuri/users/login"
someHTTPGetAPI = "https://myapi.myco.com/someuri/someuri/someservice"
username = "myuser"
password = "mypass"
headers = {
"Content-Type": "application/json",
"login": username,
"password": password
}
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
verify=False
session = requests.Session()
sessionResponse = session.get(url=loginURL,headers=headers, verify=verify)
if sessionResponse.status_code == 200:
getResponse = session.get(url=someHTTPGetAPI)
if getResponse.status_code == 200:
responseJSON = agentStatus.json()

"Error parsing JSON" when using Spotify API

I am learning Python and I am trying to create a playlist using the Spotify web api but get a http 400 error: Error parsing json. I guess it has to do with an incorrect variable type in the token but I am having a really hard time debugging it as I can't figure out a way to see the post request in raw format.
Posting through the API requires authorizing and this is the script I've created for that:
import requests
import base64
requests.packages.urllib3.disable_warnings()
client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'
def request_token():
# 1. Your application requests authorization
auth_url = 'https://accounts.spotify.com/authorize'
payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
auth = requests.get(auth_url,params = payload)
print '\nPlease go to this url to authorize ', auth.url
# 2. The user is asked to authorize access within the scopes
# 3. The user is redirected back to your specified URI
resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
resp_code= resp_url.split("?code=")[1].split("&")[0]
# 4. Your application requests refresh and access tokens
token_url = 'https://accounts.spotify.com/api/token'
payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
auth_header = base64.b64encode(client_id + ':' + client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
req = requests.post(token_url, data=payload, headers=headers, verify=True)
response = req.json()
return response
This is the function actually trying to create the playlist using the authorization token (import authorizer is the function above):
import requests
import authorizer
def create_playlist(username, list_name):
token = authorizer.request_token()
access_token = token['access_token']
auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
payload = {'name': list_name, 'public': 'false'}
r = requests.post(api_url, params=payload, headers=auth_header)
But whatever I try it only leads to a 400 error. Can anyone please point out my error here?
Solved by adding a json.dumps for the input: json.dumps(payload) and changing the payload to be 'data' and not 'params' in the request.
So the new functioning request equals:
r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)

Categories

Resources