using the put method in Spotify using python - python

I'm having trouble using the PUT method in Python. I'm trying to force a specific device to play a track on Spotify using the PUT method as described in their website https://developer.spotify.com/documentation/web-api/reference/#endpoint-start-a-users-playback to start/resume the player.
I have managed to acquire a token and used the GET method successfully with the requests library, but I'm having trouble writing a PUT command.
This is what I currently am using, but I keep getting a 400 error:
url = "https://api.spotify.com/v1/me/player/play"
payload = {"id": "f103fb953eadfb10ed89f8df3fee40be26e354ac"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % (access_token) # paste your access token in here
}
dat= {
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
}
response = requests.request("PUT", url, headers=headers, params = payload,data=dat)
print(response.status_code) # should print out 200 when you run the code
# shows whether status was valid

Related

login into Spotify through python requests module

I've been trying to connect my Spotify account using the requests module and I came across a problem
later on I tried to manipulate it on my Python code
import requests
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
response = requests.post(URL , json=payload)
print(response.status_code)
OUTPUT : 415
what went wrong ?
I don't think this is how you should interact with Spotify from code.
It has an API and you should use tokens for authentication or anything else from password.
Anyway you can try setting the correct media type when making the request:
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
headers = { 'Content-Type':'application/x-www-form-urlencoded' }
response = requests.post(URL , json=payload, headers=headers)
you cannot use this url to send post request as it has "recaptchaToken" which you need pass in your payload which is getting generated dynamically. Hence it is not a good idea to use this approach.
Instead you can use API to achieve the same.
https://github.com/plamere/spotipy

Python "requests" vs "urllib3" to AWS API Gateway

I am writing a python program that calls AWS API Gateway to reach dynamoDB.
And it all works fine when I use python "requests":
r = requests.post("https://xxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/log-entries",
data={'logbookTimestamp': timestamp, 'Name': "Fred"})
Now in order to run this as a lambda function, I want to use "urllib3" instead of "requests"
because urllib3 is included by default in lambda's python. So now I am trying to do the same with urllib3 but can't get it to work. I've read the urllib3 user guide here (https://urllib3.readthedocs.io/en/latest/user-guide.html#json) and it says I need to encode the JSON data before sending it so I've done this:
http = urllib3.PoolManager()
fields = {'logbookTimestamp': timestamp, 'Name': "Fred"}
encoded_fields = json.dumps(fields).encode('utf-8')
link = "https://xxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/log-entries"
r = http.request('POST',
link,
body=encoded_fields,
headers={'Content-Type': 'application/json'}
)
When I look at the output of both in CloudWatch I see that the data are formatted differently.
With requests:
(c084a37e-43d8-464a-9dcf-e40c28922ece) Method request body before transformations: logbookTimestamp=2020%3A12%3A15%3A20%3A11%3A02&Name=Fred
With urllib3:
(9b8d84e9-2403-462c-b25f-945a927d1e66) Method request body before transformations:
{
"logbookTimestamp": "2020:12:15:21:31:21",
"Name": "Fred"
}
and returns the following:
(9b8d84e9-2403-462c-b25f-945a927d1e66) Endpoint response body before transformations:
{
"statusCode": 500,
"headers": {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": "290"
},
"body": "\n500 Internal Server Error\nInternal Server Error\nThe server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.\n"
}
(9b8d84e9-2403-462c-b25f-945a927d1e66) Endpoint response body before transformations: {"statusCode": 500, "headers": {"Content-Type": "text/html; charset=utf-8", "Content-Length": "290"}
I can't figure out how to get the data in the format in "urllib3" that will be accepted like it is with "requests". Any thoughts? Thanks!
If you post your json as data in requests it will be submited like a html form:
"Content-Type":["application/x-www-form-urlencoded"]
If you want it to go as json, you should use
requests.post("https://xxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/log-entries", json={'logbookTimestamp': timestamp, 'Name': "Fred"})
which submits data as:
"Content-Type":["application/json"]

'InvalidRegistration' FCM when sending Push Notifications via Appium and Python

I'm getting 'InvalidRegistration' error when I try to send a push notification to my Android device.
Header:
headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
{
Body:
body = {
"to": deviceToken,
"notification": {
"body": "Welcome to blabla",
"title": "Blabla trully loves you, did you know that?",
"priority": "high"
}
Response:
200
{'multicast_id': 6053848281333651847, 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}]}
The idea is that I'm using Appium method driver.get_clipboard_text() to get a token which is already copied in device clipboard and store it in the following variable:
deviceToken = self.driver.get_clipboard_text()
Which I pass it to my JSON. Also, if I manually store the token in my variable it will successfully work and get the push notification on my device.
I've tried to use several formatting python types by using another variable where i store a previous one where I do call that method I mentioned from Appium, but without success.
Any thoughts?

Error 404 api azure translator basic program python

I started a translator project on azure.
I copy the simple test code.
import os, requests, uuid, json
subscription_key = 'KEY_IN_PORTAL_AZURE'
endpoint = 'URL_IN_PORTAL_AZURE'
path = '/translate?api-version=3.0'
params = '&from=fr&to=en'
constructed_url = endpoint + path + params
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
body = [{
'text' : 'Bonjour'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4,
ensure_ascii=False, separators=(',', ': ')))
I change the key and the endpoint but the program return
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
I delete the service and i retry same thing
There're 2 errors in the sample code.
Error 1: for the endpoint, use this one instead of copying the one from azure portal:
endpoint = 'https://api.cognitive.microsofttranslator.com/'
Error 2: in headers, please add Ocp-Apim-Subscription-Region, and it's value is the region of the Cognitive Services resource. Like below:
'Ocp-Apim-Subscription-Region':'EastUS'
You can get the region from azure portal, the screenshot is as below:
And I tested it at my side, it worked. The result as below:

QPX Express API from Python

I am trying to use Google's QPX Express API from python. I keep running into a pair of issues in sending the request. At first what I tried is this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_KEY_HERE"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
based upon the code from: urllib2 and json
When I run the above code I get the following error message:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
I searched for a solution and adapted my code based upon the following question: TypeError: POST data should be bytes or an iterable of bytes. It cannot be str
I changed my code to this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyCMp2ZnKI3J91sog7a7m7-Hzcn402FyUZo"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
data = data.encode("utf-8")
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
However, when I run this code I get the following error message:
urllib.error.HTTPError: HTTP Error 400: Bad Request
I also tried changing utf-8 to ascii but I was unsuccessful. How can I get this working properly?
Here is a solution using the excelent requests library.
import json
import requests
api_key = "YOUR API KEY HERE"
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key
headers = {'content-type': 'application/json'}
params = {
"request": {
"slice": [
{
"origin": "TXL",
"destination": "LIM",
"date": "2015-01-19"
}
],
"passengers": {
"adultCount": 1
},
"solutions": 2,
"refundable": False
}
}
response = requests.post(url, data=json.dumps(params), headers=headers)
data = response.json()
print data
I am not sure why you request is not working. Maybe it is really the request parameters that were wrong. The date definitely needs to be in the future!
False needs to be in lowercase in JSON, so you need to quote it in Python, like this "refundable" : "false". Otherwise, your query looks good (obviously you'll need to update the date). By the way, it isn't good practice to include your API key in a public forum.

Categories

Resources