I'm having a very odd syntax error in my cfscript.
stFields = {
"EligibilityQuery": {
"Patient": {
"FirstName": arguments.data.lname,
"MiddleName": "",
"LastName": arguments.data.fname,
"DateOfBirth": dateformat(arguments.data.dob,'yyyy-mm-dd'),
"Gender": arguments.data.gender,
"SSN": arguments.data.SSN,
"Address": {
"FirstLine": "",
"SecondLine": "",
"ZipCode": arguments.data.ZipCode
}
},
"NPI": "1111111"
}
};
// call API
var authorization = "Basic: " & ToBase64('username:password');
cfhttp(method="POST", url="https://mysite/api/myAPI/", result="apiResult"){
cfhttpparam(name="Authorization", type="header", value="#authorization#");
cfhttpparam(name="Content-Type", type="header", value="application/json");
cfhttpparam(type="body", value="#serializeJSON(stFields)#");
}
apiResult = deserializeJSON(apiResult.fileContent);
It's returning error on cfhttp (A script statement must end with ";".)
Error - The CFML compiler was processing:
cfhttp(method="POST", url="https://mysite/api/myAPI/", result="apiResult")
Where am I missing the ";"?
Expects a ; after cfhttp(method="POST", url="https://mysite/api/myAPI/", result="apiResult").
Are you on CF9 or CF10? Try this:
// call API
var authorization = "Basic: " & ToBase64('username:password');
httpService = new http(method = "POST", charset = "utf-8", url = "https://mysite/api/myAPI/");
httpService.addParam(name = "Authorization", type = "header", value = "#authorization#");
httpService.addParam(name = "Content-Type", type = "header", value = "application/json");
httpService.addParam(type = "body", value = "#serializeJSON(stFields)#");
apiResult = httpService.send().getPrefix();
apiResult = deserializeJSON(apiResult.fileContent);
Related
I'm very new to Postman Api testing environment, here i got to use this one https://www.getpostman.com/collections/a0afd85b4642ab7251ba
Please how do i get to extract the collection and test it as REST API
I have tried extracted these data
"item": [
{
"name": "GetCustomerSalary_BVN",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"https://login.remita.net/remita/exapp/api/v1/send/api/loansvc/data/api/v2/payday/salary/history/ph"
]
}
},
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"var merchantId = \"27768931\";",
"var apiKey = \"Q1dHREVNTzEyMzR8Q1dHREVNTw==\";",
"var apiToken = \"SGlQekNzMEdMbjhlRUZsUzJCWk5saDB6SU14Zk15djR4WmkxaUpDTll6bGIxRCs4UkVvaGhnPT0=\";",
"var d = new Date();",
"var requestId = d.getTime();",
"var randomnumber = Math.floor(Math.random() * 1101233);",
"var authorisationCode = randomnumber;",
"var apiHash = CryptoJS.SHA512(apiKey + requestId + apiToken);",
"var authorization = \"remitaConsumerKey=\" + apiKey + \", remitaConsumerToken=\" + apiHash;",
"postman.setGlobalVariable('merchantId', merchantId);",
"postman.setGlobalVariable('apiKey', apiKey);",
"postman.setGlobalVariable('requestId', requestId);",
"postman.setGlobalVariable('authorisationCode', authorisationCode);",
"postman.setGlobalVariable('authorization', authorization);",
"",
"console.log(authorization)"
]
}
}
],
but not sure of what to do next
If you want to run this collection then you can simply import it in your postman and run all APIs at once by 'Run collection'. With this, you can the see response of all APIs (in your case 6 APIs).
If you want to execute all APIs individually and manually then select each API after importing the collection and run them to see the response.
I'm trying to batch create a bunch of intents, and I want to assign an Input context
As far as I can see this should not need a session as it's just a string context name.
Like this in the GUI:
The API call I make creates the intent,
doesn't throw an error,
but I can't get the contexts to show up.
Is there some weird format to the contexts parameter?
I've exported the zip and looked at the JSON files, they're just an array of strings.
I've seen other code that seems to require a user conversation sessionId to create contexts. But the intents are global - not for a single conversation. And I assume these are just for tracking context within a single conversation session (or google astronaut engineering)
The data I'm POSTing looks like the below
There's a google example here that doesn't touch contexts
https://cloud.google.com/dialogflow/es/docs/how/manage-intents#create_intent
I've tried contexts as various formats without success
// this is the part that doesn't work
// const contexts = [{
// // name: `${sessionPath}/contexts/${name}`,
// // name: 'test context name'
// }]
const contexts = [
'theater-critics'
]
createIntentRequest {
"parent": "projects/XXXXXXXX-XXXXXXXX/agent",
"intent": {
"displayName": "test 4",
"trainingPhrases": [
{
"type": "EXAMPLE",
"parts": [
{
"text": "this is a test phrase"
}
]
},
{
"type": "EXAMPLE",
"parts": [
{
"text": "this is a another test phrase"
}
]
}
],
"messages": [
{
"text": {
"text": [
"this is a test response"
]
}
}
],
"contexts": [
"theater-critics"
]
}
}
Intent projects/asylum-287516/agent/intents/XXXXXXXX-e852-4c09-bda6-e524b8329db8 created
Full JS (TS) code below for anyone else
import { DfConfig } from './DfConfig'
const dialogflow = require('#google-cloud/dialogflow');
const testData = {
displayName: 'test 4',
trainingPhrasesParts: [
"this is a test phrase",
"this is a another test phrase"
],
messageTexts: [
'this is a test response'
]
}
// const messageTexts = 'Message texts for the agent's response when the intent is detected, e.g. 'Your reservation has been confirmed';
const intentsClient = new dialogflow.IntentsClient();
export const DfCreateIntent = async () => {
const agentPath = intentsClient.agentPath(DfConfig.projectId);
const trainingPhrases = [];
testData.trainingPhrasesParts.forEach(trainingPhrasesPart => {
const part = {
text: trainingPhrasesPart,
};
// Here we create a new training phrase for each provided part.
const trainingPhrase = {
type: 'EXAMPLE',
parts: [part],
};
// #ts-ignore
trainingPhrases.push(trainingPhrase);
});
const messageText = {
text: testData.messageTexts,
};
const message = {
text: messageText,
};
// this is the part that doesn't work
// const contexts = [{
// // name: `${sessionPath}/contexts/${name}`,
// // name: 'test context name'
// }]
const contexts = [
'theater-critics'
]
const intent = {
displayName: testData.displayName,
trainingPhrases: trainingPhrases,
messages: [message],
contexts
};
const createIntentRequest = {
parent: agentPath,
intent: intent,
};
console.log('createIntentRequest', JSON.stringify(createIntentRequest, null, 2))
// Create the intent
const [response] = await intentsClient.createIntent(createIntentRequest);
console.log(`Intent ${response.name} created`);
}
// createIntent();
update figured out based on this
https://cloud.google.com/dialogflow/es/docs/reference/rest/v2/projects.agent.intents#Intent
const contextId = 'runner'
const contextName = `projects/${DfConfig.projectId}/agent/sessions/-/contexts/${contextId}`
const inputContextNames = [
contextName
]
const intent = {
displayName: testData.displayName,
trainingPhrases: trainingPhrases,
messages: [message],
inputContextNames
};
I have over 700 Projects for which I have to create Spaces on Confluence Cloud. Doing this manually is not feasible. Have to come up with some script or tool that reads the information from Text File and creates the spaces. I have programming background - Python and Java. Can someone suggest a solution for achieving this please?
Here is the code snippet for reading the space and page names from excel and creating them in Confluence cloud -
import requests
import json
from requests.auth import HTTPBasicAuth
from openpyxl import load_workbook
from collections import defaultdict
filename = "path/PjtExport.xlsx"
wb = load_workbook(filename)
sheet = wb["Sheet1"]
confdict = defaultdict(list)
for i1 in range(2,10) :
if(str(sheet.cell(row=i1, column=1).value) != "None") :
spaceName = str(sheet.cell(row=i1, column=1).value)
keyName = spaceName.replace(" ","")
#print(keyName)
if not(confdict.keys().__contains__(spaceName)):
confdict.setdefault(keyName,spaceName)
#print(spaceName)
url = 'https://domain.atlassian.net/wiki/rest/api/space'
auth = HTTPBasicAuth('xxx#yyy.com', 'abcabcabc')
headers = {
"Accept": "application/json",
"Content-Type": "application/json"
}
payload = json.dumps({
"key": keyName,
"name": spaceName,
"description": {
"plain": {
"value": "Test space created in Python - XL Int",
"representation": "storage"
}
},
})
response = requests.request(
"POST",
url,
data=payload,
headers=headers,
auth=auth
)
res_data = response.json()
spaceID = str((res_data["homepage"]["id"]))
pageName = str(sheet.cell(row=i1, column=2).value)
url = "https://domain.atlassian.net/wiki/rest/api/content/aaaa/pagehierarchy/copy"
auth = HTTPBasicAuth('xxx#yyy.com', 'abcabcabc')
headers = {
"Content-Type": "application/json"
}
payload = json.dumps({
"copyAttachments": True,
"copyPermissions": True,
"copyProperties": True,
"copyLabels": True,
"copyCustomContents": True,
"destinationPageId": spaceID,
"titleOptions": {
"prefix": pageName + " ",
"replace": "",
"search": ""
}
})
response = requests.request(
"POST",
url,
data=payload,
headers=headers,
auth=auth
)
page_data = response.json()
#spaceID = str((res_data["homepage"]["id"]))
print(page_data)
I am creating an array of date and in my resolver it only return one output of date and count audited
I search throughout the google to find some answer and I found a code how to make an array of list but the problem is it didn't return well
https://imgur.com/a/1eDknYN
this is a result and the code I use it attached in the picture
#set ($tu = 0) #set ($pc = 0) #set ($fc = 0) #set ($da = [])#set ($cda = []) #foreach($item in $ctx.result.items)
#set($tu = $item.total_audits + $tu)
#set($pc = $item.passed_compliance + $pc)
#set($fc = $item.failed_compliance + $fc)
#set($date = $item.sort)
#set($count = $item.total_audits)
$util.qr($da.add("$date"))
$util.qr($cda.add("$count"))
#end
$util.toJson({"total_audits":$tu, "passed_compliance":$pc,
"failed_compliance":$fc, "daily_audit": [{"date": $da, "count": $cda}]})
here is the error
"errors": [
{
"path": [
"getAuditSummary",
"daily_audit",
0,
"date"
],
"locations": null,
"message": "Can't serialize value (/getAuditSummary/daily_audit[0]/date) : Unable to serialize `[2018-12-26, 2018-12-27, 2018-12-28]` as a valid date."
},
{
"path": [
"getAuditSummary",
"daily_audit",
0,
"count"
],
"locations": null,
"message": "Can't serialize value (/getAuditSummary/daily_audit[0]/count) : Expected type 'Int' but was 'ArrayList'."
what i want to make is it would return something like this
"daily_audit": [
{
"date": 2018-12-26,
"count": 1
}
{
"date": 2018-12-27,
"count": 4
}
{
"date": 2018-12-28,
"count": 2
}
]
This is happening because $da and $cda are arrays. So it's probably returning:
"daily_audit": [
{
"date": [2018-12-26,2018-12-27,2018-12-28],
"count": [1,4,2]
}
]
So, in your response mapping template, you can try something like:
#set ($tu = 0)
#set ($pc = 0)
#set ($fc = 0)
#set ($da = [])
#foreach($item in $ctx.result.items)
#set($tu = $item.total_audits + $tu)
#set($pc = $item.passed_compliance + $pc)
#set($fc = $item.failed_compliance + $fc)
#set($date = $item.sort)
#set($count = $item.total_audits)
$util.qr($da.add({"date":$date, "count":$count}))
#end
$util.toJson({"total_audits":$tu, "passed_compliance":$pc, "failed_compliance":$fc, "daily_audit": $da})
I have an API Gateway that uses velocity templates as a thin wrapper to allow users to do CRUD operations on a DynamoDB table.
I'm trying to write the update operation as dynamically as possible, but where I'm stuck is with determining type from the request body's properties from within the velocity template. This is what I'm working with:
#set($body = $input.path('$'))
#set($updateExpression = "set")
#set($expressionAttributeNames = "")
#set($expressionAttributeValues = "")
#foreach($attrName in $body.keySet())
#set($updateExpression = "${updateExpression} #$attrName = :${attrName},")
#set($expressionAttributeNames = "${expressionAttributeNames}""#${attrName}"":""${attrName}""")
#set($attrValue = $input.json("$.${attrName}"))
#if($attrValue.matches("^-?\\d+$"))
#set($attrValue = """:${attrName}"": { ""N"": ${attrValue}, ")
#else
#set($attrValue = """:${attrName}"": { ""S"": """ + $util.escapeJavaScript($attrValue) + """ },")
#end
#set($expressionAttributeValues = "${expressionAttributeValues} ${attrValue}")
#if($foreach.hasNext)
#set($expressionAttributeNames = "${expressionAttributeNames}, ")
#end
#end
{
"TableName": "TABLE",
"Key": { "id": { "S": "$input.params('id')" } },
"UpdateExpression": "${updateExpression} updatedOn = :updatedOn",
"ExpressionAttributeNames": {$expressionAttributeNames},
"ExpressionAttributeValues": {
$expressionAttributeValues
":updatedOn": { "N": "$context.requestTimeEpoch" }
}
}
Edit: This would be a sample request body:
https://api/v1/endpoint/123
{
"location": {
"lat": 42,
"lon": -71
},
"rating": 4
}
This is the current transformation I get:
{
"TableName": "users",
"Key": { "gcn": { "S": "123" } },
"UpdateExpression": "set #number = :number, #location = :location, updatedOn = :updatedOn",
"ExpressionAttributeNames": {"#number":"number", "#location":"location"},
"ExpressionAttributeValues": {
":number": { "S": "1" }, ":location": { "S": "{\"lat\":26.89199858375187,\"lon\":75.77141155196833}" },
":updatedOn": { "N": "" }
}
}
I currently just have a test for checking if a value is a number...and it isn't working.
After doing some more digging I reached what I set out for. I have a dynamic Velocity Template mapping for AWS API Gateway for the purpose of updating DynamoDB items.
So far it supports strings, numbers, booleans, and string-escaped objects, as that's how my project stores them (they are not query-able). ExpressionAttributeNames exists in case you use a reserved keyword for an attribute name...like I did for 'location'.
If anyone has any improvements/enhancements please let me know, it's a beast of a script.
#set($body = $input.path('$'))
#set($updateExpression = "set")
#set($expressionAttributeNames = "")
#set($expressionAttributeValues = "")
#foreach($attrName in $body.keySet())
#set($updateExpression = "${updateExpression} #$attrName = :${attrName},")
#set($expressionAttributeNames = "${expressionAttributeNames}""#${attrName}"":""${attrName}""")
#set($attrValue = $input.json("$.${attrName}"))
#if($attrValue.toString().matches("[+-]?\d+"))
#set($attrValue = """:${attrName}"": { ""N"": ""${attrValue}"" }, ")
#elseif($attrValue.toString() == "true" || $attrValue.toString() == "false")
#set($attrValue = """:${attrName}"": { ""BOOL"": ${attrValue} }, ")
#elseif(($attrValue.toString().startsWith("{") && $attrValue.toString().endsWith("}")) ||
($attrValue.toString().startsWith("[") && $attrValue.toString().endsWith("]")) )
#set($attrValue = """:${attrName}"": { ""S"": """ + $util.escapeJavaScript($attrValue) + """ },")
#else
#set($attrValue = """:${attrName}"": { ""S"": " + $attrValue + " },")
#end
#set($expressionAttributeValues = "${expressionAttributeValues} ${attrValue}")
#if($foreach.hasNext)
#set($expressionAttributeNames = "${expressionAttributeNames}, ")
#end
#end
{
"TableName": "", ## Insert your table here.
"Key": { "gcn": { "S": "$input.params('')" } }, ## Insert your key expression here.
## Update below if `updatedOn` is not your audit attribute.
"UpdateExpression": "${updateExpression} updatedOn = :updatedOn",
"ExpressionAttributeNames": {$expressionAttributeNames},
"ExpressionAttributeValues": {
$expressionAttributeValues
":updatedOn": { "N": "$context.requestTimeEpoch.toString()" }
}
}
Sample Request Body:
{
"firstName": "John",
"isActive": true,
"_status": 1
}
Sample Transformation:
{
"TableName": "users",
"Key": {
"id": {
"S": "1"
}
},
"UpdateExpression": "set #firstName = :firstName, #isActive = :isActive, #_status = :_status, updatedOn = :updatedOn",
"ExpressionAttributeNames": {
"#firstName": "firstName",
"#isActive": "isActive",
"#_status": "_status"
},
"ExpressionAttributeValues": {
":firstName": {
"S": "John"
},
":isActive": {
"BOOL": true
},
":_status": {
"N": "1"
},
":updatedOn": {
"N": "123456789"
}
}
}