Using python 3.6, requests==2.22.0
Trying to create an event: documentation link
url = 'https://www.googleapis.com/calendar/v3/calendars/{}/events'.format(calendar_id)
data = {
"summary": "CALENDAR TESTING",
"location": "Some fake location",
"description": "This is a test",
"start": {
"dateTime": "2019-10-09T09:00:00-07:00",
"timeZone": "America/Los_Angeles",
},
"end": {
"dateTime": "2019-10-09T10:00:00-07:00",
"timeZone": "America/Los_Angeles",
},
}
headers = {
'Authorization': 'Bearer {}'.format(self.access_token.get('token')),
'Accept': 'application/json',
'Content-Type': 'application/json',
}
response = requests.post(url, data=data, headers=headers)
print("Response: ", response)
j = response.json()
print("json: ", j)
Output:
Response: <Response [400]>
Raw Response: {'error': {'errors': [{'domain': 'global', 'reason': 'parseError', 'message': 'Parse Error'}], 'code': 400, 'message': 'Parse Error'}}
request body:
summary=CALENDAR+TESTING&location=Some+fake+location&description=This+is+a+test&start=dateTime&start=timeZone&end=dateTime&end=timeZone
request headers:
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'application/json', 'Connection': 'keep-alive', 'Authorization': 'Bearer ******', 'Content-Type': 'application/json', 'Content-Length': '135'}
Stack posts that did not fix the issue:
stack post - re not setting content type, which I am
stack post - re apostrophes vs double quotes, I switched to double quotes still error
I did notice that the timezone information is missing from the request body, but I am not sure why, and if that is the issue.
I am looking into this post right now
A simple solution to fix the problem:
import json
response = requests.post(url, data=json.dumps(data), headers=headers)
Related
Chrome devtools has a feature that allows to copy a request in the browser as node-fetch
But for some reason if I try to run this request in node it returns:
status: 403,
statusText: 'Forbidden'
I am by no means an expert on http requests, but what could be the issue of this?
The headers sent:
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'accept-language': 'de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US;q=0.6',
'cache-control': 'no-cache',
pragma: 'no-cache',
'sec-ch-ua':
'"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
},
referrerPolicy: 'strict-origin-when-cross-origin',
body: null,
method: 'GET',
Can anyone refresh me on what I am missing here?
I made this function to make it possible to send announcements to my google home mini but im getting error code 400 (Bad Request) nonstop. I tried using multiple approaches to this.
In Home-Assistant, i have setup my Google Home and can play media through it but whenever i try it with the "google_say" API of Home-Assistant it doesn't work.
I also tried calling the Home-Assistant API over my Phone using an App called "API Client" but i got the same response.
function ttsGoogleHome(text) {
var ttsUrl = "http://127.0.0.1:8123/api/services/tts/google_say?api_password=<MY_PASSWORD>"
var varToken = "<MY_TOKEN>"
var postData = {"entity_id": "media_player.david", "message": `${text}`};
let axiosConfig = {
headers: {
'authorization': `Bearer ${varToken}`,
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
}
};
axios.post(ttsUrl, postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", JSON.stringify(res));
})
.catch((err) => {
console.log("AXIOS ERROR: ", JSON.stringify(err));
})
}
This is the response i get in the server:
{
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n
at createError (/home/pi/nodejs/node_modules/axios/lib/core/createError.js:16:15)\n
at settle (/home/pi/nodejs/node_modules/axios/lib/core/settle.js:17:12)\n
at IncomingMessage.handleStreamEnd (/home/pi/nodejs/node_modules/axios/lib/adapters/http.js:260:11)\n
at IncomingMessage.emit (events.js:388:22)\n
at endReadableNT (internal/streams/readable.js:1336:12)\n
at processTicksAndRejections (internal/process/task_queues.js:82:21)",
"config": {
"url": "http://127.0.0.1:8123/api/services/tts/google_say?api_password=<MY_PASSWORD>",
"method": "post",
"data": "{\"entity_id\":\"media_player.david\",\"message\":\"Erste Stunde Fach Deutsch Lehrer Schemmer Raum Schemmer\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"authorization": "Bearer <MY_TOKEN>",
"Access-Control-Allow-Origin": "*",
"User-Agent": "axios/0.21.1",
"Content-Length": 103
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
}
I found my error.
I used the wrong api link
here is the correct way to call it.
function ttsGoogleHome(text) {
var ttsUrl = "http://127.0.0.1:8123/api/services/tts/google_translate_say?api_password=APIPASSWORD"
var varToken = "TOKEN"
var postData = `{"entity_id": "media_player.david", "message": "${text}", "language": "de"}`;
let axiosConfig = {
data: null,
headers: {
'authorization': `Bearer ${varToken}`,
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
}
};
axios.post(ttsUrl, postData, axiosConfig)
.then((res) => {
console.clear();
console.info("RESPONSE RECEIVED: ", JSON.stringify(res));
})
.catch((err) => {
console.clear();
console.error("AXIOS ERROR: ", JSON.stringify(err));
})
}
also here is my configuration.yaml:
# Configure a default steup of Home Assistant (frontend, api, etc)
# Text to speech
tts:
- platform: google_translate
- language: "de"
- service_name: google_say
-base_url: http://192.168.0.176:8123
group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
homeassistant:
auth_providers:
- type: legacy_api_password
api_password: !secret http_password
I am trying to call the createFeedDocument operation to sp-api. But I never get a response.
Here is my signedRequest:
{
path: '/feeds/2020-09-04/documents',
method: 'POST',
host: 'sellingpartnerapi-fe.amazon.com',
region: 'us-west-2',
service: 'execute-api',
headers: {
'User-Agent': 'MyAmazonApp/1.0 (Language=JavaScript;)',
'x-amz-access-token': 'Atzasd61as689d1a1f89a189198ea1f891ad89d1e891f89ae189f189165',
Accept: 'application/json',
'Accept-Charset': 'utf-8',
Host: 'sellingpartnerapi-fe.amazon.com',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Content-Length': 58,
'X-Amz-Security-Token': 'Fwa***********************************************',
'X-Amz-Date': '20210404T230040Z',
Authorization: 'AWS4-HMAC-SHA256 Credential=ASIASEECTM3DHQOSTQ4M/20210404/us-west-2/execute-api/aws4_request, SignedHeaders=accept;accept-charset;content-length;content-type;host;x-amz-access-token;x-amz-date;x-amz-security-token, Signature=f***********************************************e'
},
body: '{"contentType":"text/tab-separated-values; charset=UTF-8"}'
}
And if I tried to call this operation without body it gives the error shown below:
{
"statusCode": 400,
"res": {
"errors": [
{
"code": "InvalidInput",
"message": "One or more required parameters missing",
"details": "contentType;"
}
]
}
}
Your Content-Type header should be application/json
To send a notification, you'll need to send the following HTTP request:
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=YOUR_SERVER_KEY
{
"notification": {
"title": "New chat message!",
"body": "There is a new message in FriendlyChat",
"icon": "/images/profile_placeholder.png",
"click_action": "http://localhost:5000"
},
"to":"YOUR_DEVICE_TOKEN"
}
how can I do this??
If you're using Node.JS, I suggest you look at the documentation for Firebase's Node.JS SDK instead of manually sending HTTP requests. There's the official documentation or this nice tutorial
If you still want to go for the plain HTTP method, you can use the request npm module
$ npm install request
then in your code :
const request = require('request');
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": ['key', yourServerKey].join('=')
},
json: {
to: clientFirebaseToken,
notification: {
title: "Notification Title",
body: "This is a neat little notification, right ?"
}
});
Edit
From their GitHub
As of Feb 11th 2020, request is fully deprecated. No new changes are
expected to land. In fact, none have landed for some time.
If you use axios
axios({
method: 'post',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
"Content-Type": "application/json",
"Authorization": ['key', yourServerKey].join('=')
},
params: {
to: clientFirebaseToken,
notification: {
title: "Notification Title",
body: "Neat indeed !"
}
}
})
If you are using React JS/ React Native, using the Axios package it can be done very easily, the sample code is below, first, you have to register for firebase cloud messaging to get the authorization key
axios.post(
'https://fcm.googleapis.com/fcm/send',
{
data: {},
notification: {
title: "Sample text1",
body: "Sample text2",
image: "Sample text3",
},
to: '/topics/TopicName',
},
{
headers: {
Authorization:
'key=Authorization key from firebase',
},
},
)
.then(Response => {
console.log(Response.data);
});
I’m trying to script adding a permission in Azure AD, and I’m getting a 403 for some reason.
Here’s the command:
az ad app permission grant --id 934b23f2-ab55-4876-83ce-b38e9966ea53 --api 2ac352a9-b35a-4db8-bbce-84d9245faa45
Here’s the debug output:
msrest.http_logger : Request URL: 'https://graph.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2PermissionGrants?api-version=1.6'
msrest.http_logger : Request method: 'POST'
msrest.http_logger : Request headers:
msrest.http_logger : 'Accept': 'application/json'
msrest.http_logger : 'Content-Type': 'application/json; charset=utf-8'
msrest.http_logger : 'accept-language': 'en-US'
msrest.http_logger : 'Content-Length': '323'
msrest.http_logger : 'User-Agent': 'python/3.6.6 (Windows-10-10.0.18362-SP0) msrest/0.6.6 msrest_azure/0.6.0 azure-graphrbac/0.60.0 Azure-SDK-For-Python AZURECLI/2.0.62'
msrest.http_logger : Request body:
msrest.http_logger : {"odata.type": "Microsoft.DirectoryServices.OAuth2PermissionGrant", "clientId": "874bf2e7-d191-4d86-ba64-234c885c703a", "consentType": "AllPrincipals", "resourceId": "e7c4266c-e7c0-440f-910a-2557f24b842c", "scope": "user_impersonation", "startTime": "2019-04-18T00:11:56.102063", "expiryTime": "2020-04-18T00:11:56.102063"}
msrest.universal_http : Configuring redirects: allow=True, max=30
msrest.universal_http : Configuring request: timeout=100, verify=True, cert=None
msrest.universal_http : Configuring proxies: ''
msrest.universal_http : Evaluate proxies against ENV settings: True
urllib3.connectionpool : Starting new HTTPS connection (1): graph.windows.net:443
urllib3.connectionpool : https://graph.windows.net:443 "POST /72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2PermissionGrants?api-version=1.6 HTTP/1.1" 403 219
msrest.http_logger : Response status: 403
msrest.http_logger : Response headers:
msrest.http_logger : 'Cache-Control': 'no-cache'
msrest.http_logger : 'Pragma': 'no-cache'
msrest.http_logger : 'Content-Type': 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'
msrest.http_logger : 'Expires': '-1'
msrest.http_logger : 'ocp-aad-diagnostics-server-name': 'flQBgrwiZdgfrwyQn7i7mb8tOHe8Zm56rla4LDh9+Zw='
msrest.http_logger : 'request-id': 'e514bba2-7cc9-47e7-bd16-ff1ea17fbad8'
msrest.http_logger : 'client-request-id': '924eb878-616e-11e9-8077-f26e0bc197ab'
msrest.http_logger : 'x-ms-dirapi-data-contract-version': '1.6'
msrest.http_logger : 'ocp-aad-session-key': '-RrCLfYgOSFwqxz4IBLGEBFBrYfXBZbU8zNwiCGag-dWYfm6EGWjClVXFX9LjmWphFkDKZaqQP39ko2PuX_K4DXuqK1NwUB5wayM8e5wnXvaSoYQW1B4nwJDR7JAHnwU.e2QPHdU1fQSwX4_tnWM81ajF8thbjmTeEPBE9HPtOJI'
msrest.http_logger : 'DataServiceVersion': '3.0;'
msrest.http_logger : 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
msrest.http_logger : 'Access-Control-Allow-Origin': '*'
msrest.http_logger : 'X-AspNet-Version': '4.0.30319'
msrest.http_logger : 'X-Powered-By': 'ASP.NET'
msrest.http_logger : 'Duration': '545850'
msrest.http_logger : 'Date': 'Thu, 18 Apr 2019 00:11:55 GMT'
msrest.http_logger : 'Content-Length': '219'
msrest.http_logger : Response content:
msrest.http_logger : {"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."},"requestId":"e514bba2-7cc9-47e7-bd16-ff1ea17fbad8","date":"2019-04-18T00:11:56"}}
msrest.exceptions : Operation failed with status: 'Forbidden'. Details: 403 Client Error: Forbidden for url: https://graph.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2PermissionGrants?api-version=1.6
cli.azure.cli.core.util : Operation failed with status: 'Forbidden'. Details: 403 Client Error: Forbidden for url: https://graph.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2PermissionGrants?api-version=1.6
Operation failed with status: 'Forbidden'. Details: 403 Client Error: Forbidden for url: https://graph.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2PermissionGrants?api-version=1.6
az_command_data_logger : exit code: 1
telemetry.save : Save telemetry record of length 2468 in cache
telemetry.check : Negative: The C:\Users\mikebaz\.azure\telemetry.txt was modified at 2019-04-17 20:04:03.430973, which in less than 600.000000 s
command ran in 2.421 seconds.
And this is what I’m trying to grant:
[
{
"additionalProperties": null,
"expiryTime": "",
"resourceAccess": [
{
"additionalProperties": null,
"id": "4b7cb559-04e7-4d6e-8b59-362ceccc6a89",
"type": "Scope"
}
],
"resourceAppId": "2ac352a9-b35a-4db8-bbce-84d9245faa45"
}
]
I can successfully do the grant in the Portal (that’s how I can get the grant details above), so I know I am allowed to do the grant.
Any thoughts about what I’m missing here?
At least one issue that I notice is that value for --api parameter in your command is probably not correct.
In Json that you mention is the working copy from Portal, resourceAppId is 2ac352a9-b35a-4db8-bbce-84d9245faa45 so that should be the value of --api parameter or target API in your command.
[
{
"additionalProperties": null,
"expiryTime": "",
"resourceAccess": [
{
"additionalProperties": null,
"id": "4b7cb559-04e7-4d6e-8b59-362ceccc6a89",
"type": "Scope"
}
],
"resourceAppId": "2ac352a9-b35a-4db8-bbce-84d9245faa45"
}
]
Also make sure that you have the 934b23f2-ab55-4876-83ce-b38e9966ea53 is the applicationid or objectid for your application.
az ad app permission grant --id 934b23f2-ab55-4876-83ce-b38e9966ea53 --api 2ac352a9-b35a-4db8-bbce-84d9245faa45 --scope user_impersonation --consent-type AllPrincipals