I am trying to send a push notification from Firebase Cloud Message via AWS Lambda. The API responds with authorization error.
import requests
import json
def lambda_handler(event, context):
message = event['Message']
tokens = event['PushNotificationTokens']
for token in tokens:
data = {"notification": { "title": "My Awesome App", "body": message,}, "to": token}
data_json = json.dumps(data)
print(data_json)
headers = {'Content-type': 'application/json', 'Authorization':'AAAA…...0HuQH'}
url = 'https://fcm.googleapis.com/fcm/send'
response = requests.post(url, data=data_json, headers=headers)
jsonResponse = json.loads(response.content)
print(jsonResponse)
return jsonResponse
Everything is perfect - except the headers. You'll have to add 'Key=' before the actual key. See the code below :
headers = {'Content-type': 'application/json', 'Authorization':'Key=AAAA…...0HuQH'}
Related
I am trying to create dm
import requests
import json
url = 'https://discordapp.com/api/v6/users/#me/channels'
token = 'token'
body = {
'recipient_id': '123456789'
}
data = {'data':json.dumps(body)}
headers = {
"Authorization": token,
"Content-Type":"application/json"
}
r = requests.post(url, data=data, headers=headers)
print(r.content)
print(r.text)
This code receives response with "400: Bad request" message.
I've read this but I can't find any examples of correct usage of this request.
I finally understood my mistake, I shouldn't pass dictionary as data but should pass a str, so I changed data=data to data=json.dumps(data) and it worked
I would really appreciate some help here. I am trying to use the Spotify API to add albums to a users library. I have been struggling with a Malformed Json Payload, and am completely out of ideas.
Here is a simplified version of what I am currently sitting on
url = 'https://api.spotify.com/v1/me/albums'
payload = {'body': ['01kTgTBiZkCFY3ZH2hBH6u', '4sz6Fn4BYORRLIc1AvQwQx']}
headers = {'Authorization':'Bearer {}'.format(access_token), 'Content-Type':'application/json',}
response = requests.put(url,headers=headers, data=payload)
print(response.json())
The error I am receiving is in the json response:
{'error': {'status': 400, 'message': 'Malformed json payload'}}
I have tried changing requests.put as per below, but all attempts are returning the same error
response = requests.put(url,headers=headers, json=payload)
response = requests.put(url,headers=headers, data=json.dumps(payload))
response = requests.put(url,headers=headers, json=json.dumps(payload))
07bYtmE3bPsLB6ZbmmFi8d: This spotify id is for the album, Dancefloor Hits #1. I checked my spotify acct and there it was in my Albums on my acct. Below is my code to run that.
import requests
url = "https://api.spotify.com/v1/me/albums"
payload = {"ids": "27cZdqrQiKt3IT00338dws"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % (access_token) # paste your access token in here
}
''' you can use the same syntax as above but the key was that your ID of album had to be a **parameter** not ***data***.
To do that you use the params kwarg'''
response = requests.request("PUT", url, headers=headers, params = payload)
print(response.status_code) # should print out 200 when you run the code
# shows whether status was valid
So i'm writing a program that post's data to a url and get's the response. In postman it requires a token. So when I tried to make it in python it's giving me a response [401].
The problem I have is trying to get the token first and then passing it to my post_data method.
I'm going to put *** by the URL and username and password for privacy concerns.
import requests
import json
import pprint
import urllib
def get_token():
tokenurl='***'
data={
'grant_type':'password',
'username':'***',
'password':'***'
}
token=requests.post(tokenurl,data=data)
print(token)
get_token()
def post_data():
url1='***'
data={"***"
}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=data_json, headers=headers)
pprint.pprint(response.json())
In the post_data() function, you can add your generated token to the headers
headers = {'Content-type': 'application/json','Authorization': 'token ***'}
*** is your generated token
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 am trying to call my jwt authenticated django api that lives on an EC2 instance from my home laptop. the API will return me a auth key but when i try to use the auth key it tells me im not authorized. I have provided an example of the various methods i have tried to use to get this to work.
is there anything specifically i am doing wrong in this code that would warrant my code to consistently return 401 error? when asking for an authenticated API with a JWT token is there anything specifically i need to do or a specific way i need to set my headers so that i can get a value to return? or does this look like an issue with the backend?
import requests
from urllib2 import Request, urlopen
import jwt
from requests_jwt import JWTAuth, payload_method
import json
def tryme(chats, payload, jwt):
#method1
res = requests.post(chats, json=payload)
print res.status_code
# error 401
# method2
req = requests.get(chats, params=payload)
print req.status_code
# error 401
# method3
req = Request(chats)
req.add_header('Authorization', 'Token token={}'.format(auth['token']))
req.add_header('content-type', 'application/json')
res = urlopen(req)
print res.status_code
# error 401
#method4
token = JWTAuth(jwt['token'])
out = requests.get(chats, auth=token)
print out.status_code
# error 401
out = requests.post(chats, auth=token)
print out.status_code
# error 401
def main():
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
auth = json.loads(requests.post(api_auth, json=payload).content)
# returns auth token
payload = {'Authorization': 'Token {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'Bearer {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'JWT {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
if __name__ == '__main__':
main()
this was solved. however i upgraded to python3.
import requests
import urllib3
urllib3.disable_warnings()
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# in python3 use urllib3.
http = urllib3.PoolManager()
res = http.request('GET', chats, headers=payload)
print(res.data)
in python2:
import requests
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# make sure you are using the right request (GET vs POST)
out = requests.get(chats, headers=token)
print out.content