FCM api 'Bad request 400' error - python

I'm trying to implement sending notifications via new FCM api protocols. I went through authenticating requests, I enabled api in google console as well. Now when I send request I'm receiving Bad request 400 error. Response doesn't contain any other information than error code and error message. Even reason field says 'Bad Request'. I'm implementing it with FCM api docs.
def fcm_test():
FCM_URL = "https://fcm.googleapis.com/v1/projects/MY_PROJECT_NAME/messages:send"
my_token = "device-token"
payload = {
"massage": {
"token": my_token,
"notification": {
"body": "body",
"title": "title"
}
}
}
payload = json.dumps(payload)
headers = {
"Authorization": "Bearer {auth_token}".format(auth_token=_get_authentication_token()),
"Content-Type": "application/json; UTF-8",
}
try:
request = moves.urllib.request.Request(FCM_URL, payload.encode('utf-8'), headers)
response = moves.urllib.request.urlopen(request, timeout=10)
except Exception as e:
pass
return

There's a typo in your payload key, can you try it again with "message" instead of "massage"?

Related

send post request to itunes Reporter

I am trying to send a POST request to Itunes reporter API to download a sales report: https://help.apple.com/itc/appsreporterguide/#/apd68da36164
In the queryInput, I pass in "1234" which is the vendorId.
import requests
headers = { "access_token": "123"}
json_data = {
"version": "1.0",
"mode": "Test",
"queryInput": "[p=Reporter.properties, Sales.getReport, 1234, Sales, Summary, Daily, 20230101]"
}
response = requests.post('https://reportingitc-reporter.apple.com/reportservice/sales/v1',
headers=headers, json=json_data)
#content = response.json()
print(response.content, response.status_code)
However, looks like the way I am passing parameters is incorrect because I only get this as the response:
b'' 400
I am certain that the access token is correct but not sure if i am passing it correctly.

Spotify refresh token in Python 3

I am attempting to get a refresh token and use it to request a new access token when the temporary access token expires.
Spotify's documentation states the response body should contain the following json data:
{
"access_token": "NgCXRK...MzYjw",
"token_type": "Bearer",
"scope": "user-read-private user-read-email",
"expires_in": 3600,
"refresh_token": "NgAagA...Um_SHo"
}
However, using my code below only provides the following:
{
"access_token": "xxxx....",
"token_type": "Bearer",
"expires_in": 3600
}
I am using the following function to request an access token:
def get_access_token(client_id, client_secret): # getting access token from spotify using client ID
# Encoding Client ID and Client Secret in Base64
token_url = "https://accounts.spotify.com/api/token"
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_data = {
"grant_type": "client_credentials"
}
token_headers = {
'Authorization': f"Basic {client_creds_b64.decode()}"
}
r = requests.post(token_url, data=token_data, headers=token_headers)
valid_request = r.status_code in range(200, 299)
token_response_data = r.json()
# pretty print response body
print(json.dumps(token_response_data, indent=2)) # response 200 -> successful attempt
if valid_request:
access_token = token_response_data['access_token']
return access_token
I am unsure why the scope and refresh token are missing from the response body. How can I alter this function to include these?
Thanks in advance for your time!
Spotify documentation: https://developer.spotify.com/documentation/general/guides/authorization/code-flow/
Altering the token data fixes this:
token_data = {
"grant_type": "authorization_code",
"code": "xxxx....",
"redirect_uri": "your redirect uri from Spotify for devs"
}
You need to set up a redirect uri on Spotify for devs, then encode it to use it as a parameter.
To get the 'code' parameter fill-out this URL with your data and you will be redirected to your redirect uri.
https://accounts.spotify.com/authorize?client_id=YOUR CLIENT ID&response_type=code&redirect_uri=YOUR ENCODED REDIRECT URI&scope=playlist-modify-public%20playlist-modify-private
The code will then be in the search bar to copy/paste. It should look something like this:
https://your redirectURI?code=xxx.....
Here is a good video guide for reference:
https://www.youtube.com/watch?v=-FsFT6OwE1A&ab_channel=EuanMorgan

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:

Trying to post data to firestore using requests

im trying to post JSON data to firestore using requests and it keeps returning this error.
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message."
}
]
}
]
}
}
I've tried different method using different types of JSON Encoding and still returns the same error. i would appreciate if someone could look into this for me. Below is my code
def thestream(self, instance):
app = App.get_running_app()
s = requests.Session()
self.data = {u'data': u'message'}
self.headers = {"authorization": "bearer " + app.idToken}
r = s.post("https://firestore.googleapis.com/v1/projects/*******************************/databases/(default)/documents/messages/TemitayoAdefemi", params=json.dumps(self.data), headers=self.headers)
print(r.ok)
print(r.content.decode())
Try defining a Document resource in your payload:
self.data = {u'fields': {u'data': {u"stringValue": u'message'}}}
In your POST request, try passing the payload in data=self.data instead of param:
r = s.post("https://firestore.googleapis.com/v1/projects/***/databases/(default)/documents/messages/TemitayoAdefemi", data=self.data, headers=self.headers)

Google URL Shortener API with python returning error

I'm trying to call the Google URL Shortener API in my python code:
def shorternUrl():
API_KEY = "AIzaSyCvhcU63u5OTnUsdYaCFtDkcutNm6lIEpw"
apiUrl = 'https://www.googleapis.com/urlshortener/v1/url'
longUrl = "http://www.cnn.com"
headers = {"Content-type": "application/json"}
data = {"longUrl": longUrl}
h = httplib2.Http('.cache')
try:
headers, response = h.request(apiUrl, "POST", urllib.urlencode(data), headers)
print response
except Exception, e:
print "unexpected error %s" % e
But I keep getting this error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
I'm not using the Google API for Python. Where i'm I going wrong?
You need to send JSON in a POST, not URL encoded data:
import json
# Rest of your code
headers, response = h.request(apiUrl, "POST", json.dumps(data), headers)

Categories

Resources