« Back to full topics list
0
0

I’m trying to use a script in an API.AI Fulfillment (eventually in a Google Assistant Action). The requirements for this seem fairly rigid. https://api.ai/docs/fulfillment#response

The response needs to have a certain format:
Headers:
Content-type: application/json

Body:
{
“speech”: “Barack Hussein Obama II was the 44th and current President of the United States.”,
“displayText”: “Barack Hussein Obama II was the 44th and current President of the United States, and the first African American to hold the office. Born in Honolulu, Hawaii, Obama is a graduate of Columbia University and Harvard Law School, where “,
“data”: {…},
“contextOut”: […],
“source”: “DuckDuckGo”
}

The closest I seem to get is:
“response”: {
“metadata”: {
“requestId”: “67a51a8e-ac83-4871-8b5d-41d3c8ea52f5”,
“status”: “success”,
“statusCode”: “200”
},”result”: {
“speech”: “Hello World.”,
“displayText”: “Hello World.”,
“source”: “scriptr.io”
}
}}

Is it possible to have more control of the output format and response headers?

ANSWERED
Marked as spam
Posted by - Asked on October 6, 2017 5:44 pm - 15 views

2 Replies

0
Private reply

Hi Tony,

You can certainly have full control over your response by manipulating the response built-in object using the methods described here: https://www.scriptr.io/documentation#documentation-response.

In your case, you need to call the response.setHeader(“Content-Type”, “application/json”) method to set the “Content-Type” to “application/json”. And you also need call the response.write() method to write your stringified JSON object to the response. Don’t forget to call response.close() when you’re done to flush the data to the response stream and close it.

This is how your script would look like:

var result = {
	"speech" : "Barack Hussein Obama II was the 44th and current President of the United States.",
	"displayText" : "Barack Hussein Obama II was the 44th and current President of the United States, and the first African American to hold the office. Born in Honolulu, Hawaii, Obama is a graduate of Columbia University and Harvard Law School, where ",
	"data" : {
		"…" : "…"
	},
	"contextOut" : ["…"],
	"source" : "DuckDuckGo"
};
response.write(JSON.stringify(result));

// Set the "Content-Type" header value to "application/json"
response.setHeader("Content-Type", "application/json");

// Whenever you manipulate the response object make sure to add your CORS settings to the header so that the script works when you're running it from within your scriptr.io Workspace
response.addHeaders(configuration.crossDomainHeaders);

response.close();

I hope this helps.

Best Regards,

Julien Mrad
Scriptr.io

Marked as spam
Posted by - Replied on October 6, 2017 8:28 pm
0
Private reply

Thank you. That works great.

Marked as spam
Posted by - Replied on October 7, 2017 2:01 pm