I am trying to work with an API (that provides data about movies in the media centers of german public broadcasting) but I can't get a single useful response.
I got an example code in javascript but since I dont know anything about that language I try to understand as much as I can and write an equivalent python program. Can someone tell me my mistake? The code should return a list of movies along with their duration and some similar information.
The original goes like:
`
const query = {
queries: [
{
fields: ['title', 'topic'],
query: 'sturm der liebe'
},
{
fields: ['channel'],
query: 'ard'
}
],
sortBy: 'timestamp',
sortOrder: 'desc',
future: false,
offset: 0,
size: 10,
duration_min: 20,
duration_max: 100
};
const queryString = JSON.stringify(query); // I think this turns query into a json file
const request = new XMLHttpRequest(); // here I start to loose the understanding
const requestURL = 'https://mediathekviewweb.de/api/query';
request.open("POST", requestURL);
request.addEventListener('load', function (event) {
let response;
try {
response = JSON.parse(request.responseText);
} catch (e) { }
if (request.status == 200 && typeof response != 'undefined') {
for (let i = 0; i < response.result.results.length; i++) {
let entry = response.result.results[i];
let row = $('<tr>');
row.append($('<td>').text(entry.channel));
row.append($('<td>').text(entry.topic));
row.append($('<td>').text(entry.title));
row.append($('<td>').text(entry.description));
row.append($('<td>').text(entry.url_video));
$('#mediathek > tbody').append(row);
}
$('#responseText').text(JSON.stringify(response, null, 2));
} else {
if (response) {
console.log(response.err);
$('#errorText').html(response.err.join('</br>'));
}
else {
$('#errorText').html(request.statusText + '</br>' + request.responseText);
}
}
});
request.send(queryString);
`
I started using requests:
`
import requests
import json
url = "https://mediathekviewweb.de/api/query"
answer = requests.post(url, json=queryString)
print(answer)
print(json.loads(answer.content))
`
Already in this minimal example answer returns "<Response [400]>" and the content is "{'result': None, 'err': ['Unexpected token o in JSON at position 1']}"
Can someone help me out? I didn't give a json, where does this error come from?
I get the same response when I try
`
import requests
import json
url = "https://mediathekviewweb.de/api/query"
query = {
"queries": [], // I want to search through all movies so this is left clear
"sortBy": "timestamp",
"sortOrder": "desc",
"future": False,
"offset": 0,
"size": 1000,
"duration_min": 90,
"content-type": "text/plain"
}
queryString = json.dumps(query) # hopefully this is equivalent to JSON.stringify()
answer = requests.post(url, json=queryString)
print(answer)
print(json.loads(answer.content))
`
I actually think this extra code isn't even used by the program.
I don't know if thats the right direction, but I think the javascript programm first opens a request and then in an other step inputs the data. I can't do that with the requests package as far as I know.
Don't use XMLHttpRequest. This adds to the confusion.
Here is the fetch option:
const query = {
queries: [
{
fields: ['title', 'topic'],
query: 'sturm der liebe',
},
{
fields: ['channel'],
query: 'ard',
},
],
sortBy: 'timestamp',
sortOrder: 'desc',
future: false,
offset: 0,
size: 10,
duration_min: 20,
duration_max: 100,
};
const requestURL = 'https://mediathekviewweb.de/api/query';
fetch(requestURL, { method: 'POST', body: JSON.stringify(query) })
.then((res) => res.json())
.then((res) => {
// success request logic
console.log('response', res);
})
.catch((error) => {
// error handling
console.error(error);
});
Related
I am working on a project for a Chrome Extension I am creating where it uses Google Sheets as a "database". I have the create and get part down. However, I am struggling with the update part. Here is my code so far:
let init = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_ID}/values/All Escalations!A5:Z10000001",
init)
.then((data) => {
return data.json();
}).then ((completedata) => {
const numRows = completedata.values ? completedata.values.length: 0
console.log(`${numRows} rows retrieved`)
let source = completedata.values;
const input = source.filter(function (row, index) {
row.unshift(index);
return row;
}).filter(function (iRow) {
return iRow[1] === arcaseiddis;
});
var index = (input[1]) ; //Saves the old index
let arjira2 = document.getElementById('jiracard').value
let ardatesubmitteddis2 = document.getElementById('datesubmitted').value
let arsubmittedbydis2 = document.getElementById('submittedbyaredit').value
let arclientiddis2 = document.getElementById('clientidaredit').value
let arcasenumberdis2 = document.getElementById('casenoaredit').value
let arnotesdis2 = document.getElementById('notesaredit').value
let arstatusdis2 = document.getElementById('statusaredit').value
let arissuedis2 = document.getElementById('casedesaredit').value
let arassignedtodis2 = document.getElementById('assignedtoaredit').value
let datearcompleted = document.getElementById('datecompletearedit').value
let arcaseiddis2 = e.target.parentElement.dataset.id
input[0]= arcaseiddis2; //Update the row with stuff
input[1] = arcasenumberdis2;
input[2]= arjira2;
input[3]= arstatusdis2;
input[4]= arissuedis2;
input[5]= arclientiddis2;
input[6]= ardatesubmitteddis2;
input[7]= arsubmittedbydis2;
input[8]= arassignedtodis2
input[9]= datearcompleted
input[10]= arnotesdis2
let values = [
[
input[0],
input[1],
input[2],
input[3],
input[4],
input[5],
input[6],
input[7],
input[8],
input[9],
input[10]
]
];
const resource = {
values
};
console.log(values)
I am able to console.log this out and it actually shows the updates I put in. However, when I run the update function it gives the following error:
{range: "All Escalations!Aundefined:Jundefined", values: {values: [,…]}}
range
:
"All Escalations!Aundefined:Jundefined"
values
:
{values: [,…]}
values
:
[,…]
0
:
["82389566743686", "4306203", "None", "SUBMITTED", "Testing", "Client", "2/8/2023", "John SMith",…]
0
:
"82389566743686"
1
:
"4306203"
2
:
"None"
3
:
"SUBMITTED"
4
:
"Testing"
5
:
"Client"
6
:
"2/8/2023"
7
:
"John Smith"
8
:
"Carey Jones"
9
:
""
10
:
"No Notes Yet"
This is the update function I am running:
var payload = {
"range": "All Escalations!A" + index + ":J" + index,
"values": resource
}
let init = {
method: 'PUT',
async: true,
headers: {
Authorization: 'Bearer ' + token,
},
body: JSON.stringify(payload)
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/{SpreadsheetID}/values/All Escalations/?valueInputOption=USER_ENTERED",
init)
})
The code I've used so far is mainly coming from this article: google sheets api v4 update row where id equals value
Because this is a Chrome Extension I can't connect to the api via the URL like we used to in MV2. So I do it via the "fetch" method and it works for the get part. From looking over the above article, it looks like the person does the "get" to get that specific row. Then updates the specific row based on the ID. I appreciate any help I can get.
With some tinkering around I found the answer:
I credit Take A Minute with getting me in the right direction with his snippet. google sheets api v4 update row where id equals value. I am just starting out at this so any input on how to make this more efficient is welcome.
function updatearescalation(){
chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) { // this seems to be the best way to get the token to be able to make these requests.
let initdarread = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1uXGfr5OvJjW2Pb9YhkbLHED3cQcJI5YsvJKLedAHRKY/values/All Escalations!A5:Z10000001",
initdarread)
.then((data) => {
return data.json();
}).then ((completedata) => {
const numRows = completedata.data ? completedata.data.length: 0
console.log(`${numRows} rows retrieved`)
source = completedata.values;
const input = source.filter(function (row, index) {// when I use the source.map it returns a random row instead of the specific row I want.
row.unshift(index);
return row;
}).filter(function (iRow) {
return iRow[1] === arcaseiddis;
});
var index = parseInt(input[0]) + 5; //Saves the old index The +5 indicates where the actual data starts. This is important.
input[0].shift(); //According to post previously mentioned this removes the old index.
input[0] // This is where you update the rows with what you want.
let values = [
input[0], // This is where all the values you want updated go.
];
const resource = {
values
};
var payload = {
"range": "All Escalations!A" + index + ":K" ,
"values": resource
}
let range = "All Escalations!A" + index + ":K"
let initarupdate = {
method: 'PUT',
async: true,
headers: {
Authorization: 'Bearer ' + token,
},
body: JSON.stringify(payload)
};
fetch(
`https://sheets.googleapis.com/v4/spreadsheets/1uXGfr5OvJjW2Pb9YhkbLHED3cQcJI5YsvJKLedAHRKY/values/${range}/?valueInputOption=USER_ENTERED`,
initarupdate)
}) // I used a literal here to be able to use the Range I put in the payload.
}
}
Using this node-ews package, I can send email, but I haven't been able to find a good example of how to read mails from the Inbox folder and get the email's text and attachments.
I've read the Microsoft documentation, such as this one: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-work-with-exchange-mailbox-items-by-using-ews-in-exchange#get-an-item-by-using-the-ews-managed-api, but the examples are in C#, C++, or VB.
However, I would like to use Nodejs for this.
**I have found a best way extract every content using mailparser. see bellow
// At first Read emails from Inbox
const EWS = require('node-ews');
const simpleParser = require('mailparser').simpleParser;
// exchange server connection info
const ewsConfig = {
username: 'username',
password: 'password',
host: 'hostname'
};
const options = {
rejectUnauthorized: false,
strictSSL: false
};
// initialize node-ews
const ews = new EWS(ewsConfig, options);
var ewsFunction = 'FindItem';
var ewsArgs = {
'attributes': {
'Traversal': 'Shallow'
},
'ItemShape': {
't:BaseShape': 'Default'
},
'ParentFolderIds' : {
'DistinguishedFolderId': {
'attributes': {
'Id': 'inbox'
}
}
}
};
// Itreate over all the emails and store Id and ChangeKey.
ews.run(ewsFunction, ewsArgs, ewsSoapHeader)
.then(result => {
// Iterate over the result and extract Id and ChangeKey of the messages and pass those to GetItem function to read messages
})
// For reading individual messages returned by FindItem (using Id and ChangeKey)
var ewsFunction = 'GetItem';
var ewsArgs = {
'ItemShape': {
'BaseShape': 'Default',
'AdditionalProperties': {
'FieldURI': [
{ 'attributes': { 'FieldURI': 'item:MimeContent'}}
]
}
},
'ItemIds': {
'ItemId': {
'attributes': {
'Id': Id,
'ChangeKey': ChangeKey
}
}
}
};
await ews.run(ewsFunction, ewsArgs, ewsSoapHeader)
.then(result => {
// Iterate over the result and extract meesage
const {Message} = result.ResponseMessages.GetItemResponseMessage.Items
let mimeContent = Buffer.from(Message.MimeContent['$value'], 'base64').toString('binary');// decode mime content
simpleParser(mimeContent).then(async function (mail) {
console.log("mail")
console.log(mail.attachments)
console.log(mail.headers.get('message-id'))
console.log(mail.headers.get('references'))
console.log(mail.headers.get('in-reply-to'))
console.log({
// text: mail.text,
// html: mail.html ? mail.html.replace(/<meta([^>]+)>/g, "") : "",
from: (mail.from) ? mail.from.value.map(item => item.address) : [],
to: (mail.to) ? mail.to.value.map(item => item.address) : [],
cc: (mail.cc) ? mail.cc.value.map(item => item.address) : [],
bcc: (mail.bcc) ? mail.bcc.value.map(item => item.address) : [],
messageId: mail.messageId,
subject: mail.subject
})
}).catch((err) => {
console.log("err")
console.log(err)
})
})
Here you will get the full parsed mail contents with attachments. Happy Coding!!!
const network = {
blockchain:'eos',
protocol:'https',
host:'jungle2.cryptolions.io',
port:443,
chainId: 'e70aaab8997e1dfce58fbfac80cbbb8fecec7b99cf982a9444273cbc64c41473',
sign: true,
broadcast: true,
debug: true,
verbose: false,
}
try {
const scatterInfo = await ScatterJS.scatter.connect('eosbetdice');
console.log({scatterInfo})
if ( scatterInfo ) {
const scatter = ScatterJS.scatter;
const requiredFields = { accounts:[network] };
const scatterVal = await scatter.getIdentity(requiredFields);
console.log({scatter,scatterVal})
if ( scatterVal ) {
const account = scatter.identity.accounts.find(x => x.blockchain === 'eos');
console.log("account",account)
const result = await api.transact({
actions: [{
account: 'eosio.token',
name: 'transfer',
authorization: [{
actor: account.name,
permission:'active',
signatures:[signature],
available_keys:[account.publicKey]
}],
data: {
from: 'abceristest2',
to: account.name,
quantity: betAsset,
memo: memo
},
}]
}, {
blocksBehind: 3,
expireSeconds: 30,
});
console.log({result})
return result;
}
} return false;
} catch ( exception ) {
console.log( exception )
}
I expect the transfer function will be work fine but It give me 401 unauthorized error. This transfer function hit the api of jungle testnet , "http://jungle.eosgen.io/v1/chain/get_required_keys"
How I can authenticate this function?
Error which I got, when this transfer function run
I don't check your codes in detail, but I think it is needed to set the data of "abceristest2" to authorization parameter.
I am trying to say:
select * from myTable where pkName in ('john', 'fred', 'jane')
but there doesn't seem to be a native way to feed a list of items in an array. I have my query working and retrieving values for a single primary key but want to be able to pass in multiple ones. It seems this isn't possible from looking at the DynamoDb page in the console but is there a good workaround? Do I just have multiple OR in my KeyConditionExpression and a very complex ExpressionAttributeValues?
I'm referencing this page:
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html
And using code based on the following (which can be found at the address below):
var params = {
ExpressionAttributeValues: {
':s': {N: '2'},
':e' : {N: '09'},
':topic' : {S: 'PHRASE'}
},
KeyConditionExpression: 'Season = :s and Episode > :e',
ProjectionExpression: 'Title, Subtitle',
FilterExpression: 'contains (Subtitle, :topic)',
TableName: 'EPISODES_TABLE'
};
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html
You are looking for the batchGetItem function, documented here.
You can also use DocumentClient and batchGet.
const AWS = require('aws-sdk');
const dbClient = new AWS.DynamoDB.DocumentClient({ region: 'ap-south-1' });
exports.handler = (event, context, callback) => {
var cartItems=JSON.parse(event.body);
let scanningtable = {
RequestItems: {
COOLERS : {
Keys: [
{
"ITEM_ID": 379
},
{
"ITEM_ID": 376
}
],
ProjectionExpression: "ITEM_ID, #N,CATEGORY, SUB_CATEGORY, BRAND, SELL_RATE",
ExpressionAttributeNames: {
"#N": "NAME"
},
}
}
};
dbClient.batchGet(scanningtable, function (err, data) {
if (err) {
callback(err, null);
} else {
var response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify(data),
};
callback(null, response);
}
});
};
I am trying to use Watson translator service from my node.js app through the API documentation from IBM https://www.ibm.com/watson/developercloud/alchemyvision/api/v1/#apiexplorer
var request = require("request");
var LanguageTranslatorV3 = require('watson-developer-cloud/language-translator/v3');
var english_message
var languageTranslator = new LanguageTranslatorV3({
version: '2018-05-01',
username: '1234',
password: '1234',
url: 'https://gateway.watsonplatform.net/language-translator/api'
});
function translatorEnglish(message) {
var parameters = {
text: message.text,
model_id: 'es-en'
};
languageTranslator.translate(
parameters,
function(error, response, body) {
if (error)
console.log(error)
else
console.log(JSON.stringify(response, null, 2));
}
);
}
I get the following correct response in logs
{
"translations": [
{
"translation": "Hi."
}
],
"word_count": 1,
"character_count": 4
}
but when i try to extract the output translation value i always get the output as Undefined.
console.log(response.translations.translation); => undefined
Can you please check and let me know if i am doing anything wrong?
Thanks
Try
console.log(response.translations[0].translation); // Hi
This is because translations is an array and has one item at index 0.
{
"translations": [
{
"translation": "Hi."
}
],
"word_count": 1,
"character_count": 4
}