Add API KEY to a Get request for Alexa Skill - node.js

Im trying to add the API key to my Get request below? I have an example without the API key working below.
This is my Node.js code that is supposed to parse the JSON.
{ await getRemoteData(''https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c'
}')
.then((response) => {
const data = JSON.parse(response);
outputSpeech = `This is the name ${data[2].name} man look at that on a saturday morning.`;
}
See JSON format for the above GET request below.
This is the API URL but you need an API key to access it.
https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
JS eval
{
"0":{
"type":"coin",
"logoFile":"logos\/1.png",
"name":"Bitcoin",
"symbol":"BTC",
"price":5336.7412403400003313436172902584075927734375,
"marketcap":94232174265.99346923828125,
"volume":12689683492.3271999359130859375,
"rank":1,
"change":{
"hour":-0.0089407500000000007800426971016349853016436100006103515625,
"day":-0.139828000000000007840839089112705551087856292724609375,
"week":5.0347799999999995890220816363580524921417236328125
}
},
"1":{
"type":"coin",
"logoFile":"logos\/1027.png",
"name":"Ethereum",
"symbol":"ETH",
"price":172.80222112600000627935514785349369049072265625,
"marketcap":18273315192.039081573486328125,
"volume":5874660289.064609527587890625,
"rank":2,
"change":{
"hour":-0.11684999999999999553690344100687070749700069427490234375,
"day":-1.2512700000000001043787278831587173044681549072265625,
"week":5.626129999999999853343979339115321636199951171875
}
},
This is a working example of me parsing a JSON without an API key that works fine with a similarly formatted JSON.
await getRemoteData('https://api.coinmarketcap.com/v1/ticker/')
.then((response) => {
const data = JSON.parse(response);
outputSpeech = `This is the name ${data[2].name} man look at that on a saturday morning.`;
})
This is the API LINK below.
https://api.coinmarketcap.com/v1/ticker/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "5260.8494713",
"price_btc": "1.0",
"24h_volume_usd": "13764287489.0",
"market_cap_usd": "92951055841.0",
"available_supply": "17668450.0",
"total_supply": "17668450.0",
"max_supply": "21000000.0",
"percent_change_1h": "0.14",
"percent_change_24h": "-0.28",
"percent_change_7d": "-1.42",
"last_updated": "1556377650"
},
{
"id": "ethereum",
"name": "Ethereum",
"symbol": "ETH",
"rank": "2",
"price_usd": "156.835413228",
"price_btc": "0.02983922",
"24h_volume_usd": "6040899613.44",
"market_cap_usd": "16598483757.0",
"available_supply": "105833774.0",
"total_supply": "105833774.0",
"max_supply": null,
"percent_change_1h": "0.45",
"percent_change_24h": "1.04",
"percent_change_7d": "-9.81",
"last_updated": "1556377642"
},
{
"id": "ripple",
"name": "XRP",
"symbol": "XRP",
"rank": "3",
"price_usd": "0.2965559184",
"price_btc": "0.00005642",
"24h_volume_usd": "890277280.659",
"market_cap_usd": "12456821485.0",
"available_supply": "42004966728.0",
"total_supply": "99991643723.0",
"max_supply": "100000000000",
"percent_change_1h": "0.21",
"percent_change_24h": "0.8",
"percent_change_7d": "-10.2",
"last_updated": "1556377622"
},

Related

Unable to retrive ordered job list from Google Transcoder API

i'm using the node.js client library of google transcoder api. I'm able to retrive a paginated list of some jobs, but i'm not able to order elements by start date. Here my codes:
const { TranscoderServiceClient } = require('#google-cloud/video-transcoder').v1;
class TranscoderApiController {
constructor() {
this.projectId = process.env.GOOGLE_CLOUD_PROJECT;
this.location = process.env.TASK_LOCATION;
}
async getEntries(req, res, next) {
const params = {
pageSize: req.query.pageSize ? parseInt(req.query.pageSize) : 10,
pageToken: req.query.pageToken,
filter: req.query.filter,
orderBy: req.query.orderBy
}
const client = new TranscoderServiceClient();
const result = await client.listJobs({
parent: client.locationPath(this.projectId, this.location),
pageSize: params.pageSize,
orderBy: 'createTime.seconds'
}, {
autoPaginate: false
});
if (result.length == 3 && result[2] != undefined) {
return result[2];
} else {
return result[1];
}
}
}
module.exports = new TranscoderApiController();
When i call the getEntries method i receive the following error:
"3 INVALID_ARGUMENT: The request was invalid: sort order \"createTime.seconds\" is unsupported"
If i remove the orderBy: 'createTime.seconds' line then the api works but is not ordered as i want. The result is something like that (i abbreviate the json):
{
"jobs": [
{
"labels": {},
"name": "projects/<id>/locations/europe-west1/jobs/<uuid>",
"inputUri": "",
"outputUri": "",
"state": "SUCCEEDED",
"createTime": {
"seconds": "1656602896",
"nanos": 386772728
},
"startTime": {
"seconds": "1656602900",
"nanos": 755000000
},
"endTime": {
"seconds": "1656603062",
"nanos": 428000000
},
"ttlAfterCompletionDays": 30,
"error": null,
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://<url>/render_md.mp4",
"preprocessingConfig": null
}
],
"editList": [...],
"elementaryStreams": [...],
"muxStreams": [...],
"manifests": [],
"adBreaks": [],
"spriteSheets": [],
"overlays": [],
"output": {
"uri": "gs://<url>/md.mp4/"
},
"pubsubDestination": {
"topic": "projects/<id>/topics/transcoder_api"
}
},
"jobConfig": "config"
},
...
],
"unreachable": [],
"nextPageToken": "Co8BCjgKDGV1cm9wZS13ZXN0MRIZdHJhbnNjb2Rlci5nb29nbGVhcGlzLmNvbRgBII..."
}
As you can see each job have the startTime.seconds property. I follow the syntax described here:
https://google.aip.dev/132#ordering
Any support to solve the ordered issue is appreciated.

How to perform a filter on a json result using python

I have the json response below returned from an api call.
{
"custAnalysis": [
{
"custPermId": "1234",
"custType": "Business",
"taxId": "8888",
"custAddr": {
"fullName": "Testing LIMITED",
"addr1": "6734 APAPA RD"
}
},
{
"custPermId": "5678",
"custType": "Business",
"taxId": "9999",
"custAddr": {
"fullName": "SUPERMAN LLC",
"addr1": "6734 APAPA RD"
}
},
{
"custPermId": "9234",
"custType": "Business",
"taxId": "8888",
"custAddr": {
"fullName": "DONALD LLC",
"addr1": "6734 APAPA RD"
}
}
]
}
I want to be able to search the json result above for a taxId of 8888. If taxId = 8888
return another json in the format below with the result
{
"custQueryResult": {
"custPermId": 1234,
"custPermId": 9234
}
}
I am very new to python. How can I achieve this in Python?
search_texId=8888
search_result={"custQueryResult":[]}
for obj in response_dict["custAnalysis"]:
if int(obj["taxId"])==search_texId:
search_result["custQueryResult"].append({"custPermId": int(obj["custPermId"])})
print(search_result)
Dictionary couldn't assign the same name keys. SocustPermId will be listed under custQueryResult key

Can you 'filter' the columns from a second leftJoinAndMapOne?

Can the columns of a second leftJoinAndMapOne() be 'filtered' so that it only returns the columns or values that I need inside the object?
Query Builder:
const favorites = await this.favoritesRepo.createQueryBuilder('favorite')
.where('favorite.user_id = :token', { token })
.leftJoinAndMapOne('favorite.item', 'favorite.item_id', 'items')
.select(['favorite.id'])
.addSelect([
'items.title',
'items.description',
'items.price',
'items.stock',
])
.leftJoinAndMapOne(
'items.photos',
PhotosEntity,
'photos',
'favorite.item_id = photos.subject_id and photos.subject_type = :item',
{item: 'item'}
)
return paginate<Favorite>(favorites, options)
Output (GET):
//...
{
"id": 32,
"item": {
"title": "Foo",
"description": "Buzz",
"price": 250.99,
"stock": 10,
"photos": {
"id": 2,
"createdAt": "2021-12-04T04:55:02.408Z",
"url": "https://images.unsplash.com/photo-1633114128729-0a8dc13406b9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80",
"width": 324,
"height": 281,
"size": 42,
"entityId": 18,
"entityType": "item",
"redirectUrl": "https://facebook.com/"
}
}
},
//...
Expected Output:
//...
{
"id": 32,
"item": {
"title": "Foo",
"description": "Buzz",
"price": 250.99,
"stock": 10,
"photos": {
"url": "https://images.unsplash.com/photo-1633114128729-0a8dc13406b9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80"
}
}
},
//...
Any suggestions or changes that I should make to make the output as expected? 🤔
.leftJoinAndMapOne(
'items.image',
PhotosEntity,
'photos',
'favorite.item_id = photos.subject_id and photos.subject_type = :item',
{item: 'item'}
)
.addSelect('photos.url')
I tried with .select () or .addSelect () but it doesn't filter columns from photos.
I already resolved it
Query Builder:
const favorites = await this.favoritesRepo.createQueryBuilder('favorite')
.where('favorite.user_id = :token', { token })
.leftJoinAndMapOne('favorite.item', 'favorite.item_id', 'items')
.leftJoinAndMapOne(
'items.photos',
PhotosEntity,
'photos',
'favorite.item_id = photos.subject_id and photos.subject_type = :item',
{item: 'item'}
)
.select(['favorite.id'])
.addSelect([
'items.title',
'items.description',
'items.price',
'items.stock',
'photos.url',
])

how to find liked posts with user id

i am developing project using nodejs. I want to check if the user's userId is the same as the user of the post like. How should I be able to check ?
const audio = await Audio.find({likes: userId})
This is the post data i want to find
{
"title": "Điêu Toa",
"music": "public/audio/music_6149812c44cf4d33f410d680_1633941621172.mp3",
"singer": "Massew x Pháo",
"size": "2.72mb",
"date": {
"$date": "2021-10-11T08:37:42.840Z"
},
"owner": "6149812c44cf4d33f410d680",
"description": "Lời nói cứ như là bạc là vàng có ta và chàng ngồi ở đây chứng dám cho, chẳng việc gì phải lắng lo ~~",
"category": "Electronic",
"__v": 48,
"likes": [{
"user": "616c09216e4b2ff62f550c39"
}, {
"user": "6149812c44cf4d33f410d680"
}]
}
You could do it like that
const audio = await Audio.find({likes: {$elemMatch: {user: userId}}})

how to display the api data using jsreport studio

Html Code:
<h3>Hello Welcome</h3>
<div>{{jsonData}}</div>
Script Code:
function beforeRender(req, res, done) {
require('request')({
url:'http://samples.openweathermap.org/data/2.5/weather? lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1',
json:true,
method: 'GET'
}, function(err, response, body){
console.log(JSON.stringify(body));
req.data = { jsonData: body };
done();
});
}
The api is returns following Json Data:
{
"coord": {
"lon": 139.01,
"lat": 35.02
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 285.514,
"pressure": 1013.75,
"humidity": 100,
"temp_min": 285.514,
"temp_max": 285.514,
"sea_level": 1023.22,
"grnd_level": 1013.75
},
"wind": {
"speed": 5.52,
"deg": 311
},
"clouds": {
"all": 0
},
"dt": 1485792967,
"sys": {
"message": 0.0025,
"country": "JP",
"sunrise": 1485726240,
"sunset": 1485763863
},
"id": 1907296,
"name": "Tawarano",
"cod": 200
}
This is the jsreport generation code. Now am trying to get the data through the rest api. I don't know how the api data is print in console, i need help to how to iterate using jsrender following json data and display in console.
the out will comes in all the jsreport http ajax in following object in script section
"jsreport.data"
In this object will have all our data. you just print the following code in script
console.log("data is available are :",jsreport.data);

Resources