The following code gives me the error "Invalid request payload. Refer to the REST API documentation and try again" when is executed and I dont know where the error is
const bodyData =
`"fields": {
"summary": "Summit 2019 is awesome!",
"issuetype": {
"name": "Task"
},
"project": {
"key": "PRB"
},
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "This is the description.",
"type": "text"
}
]
}
]
}
}`;
fetch('https://mysite.atlassian.net/rest/api/3/issue', {
method: 'POST',
headers: {
'Authorization': `Basic ${Buffer.from('myemail#gmail.com:mytoken').toString('base64')}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: bodyData
}).then(response => {
console.log(
`Response: ${response.status} ${response.statusText}`
);
return response.text();
}).then(text => console.log(text)).catch(err => console.error(err));
Problem
Your bodyData is not a valid json
Solution
Wrap it with {}
`{
fields: {
"summary": "Summit 2019 is awesome!",
"issuetype": {
"name": "Task"
},
"project": {
"key": "LOD"
},
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "This is the description.",
"type": "text"
}
]
}
]
}
}
}`
P.S.
You would find this error if you would use JSON.stringify with an object instead of a string.
const bodyData = JSON.stringify(
{
fields: {
"summary": "Summit 2019 is awesome!",
"issuetype": {
"name": "Task"
},
"project": {
"key": "LOD"
},
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "This is the description.",
"type": "text"
}
]
}
]
}
}
});
Related
I'm currently facing an issue with my datatable implemented in ReactJS. I'm retrieving data from elasticsearch and populating the datatable with it. The data retrieval process works fine without the filter applied, however, when I apply filters to the data, the datatable remains empty, even though the data _source has matching records.
The structure of the parameters I am sending is as follows:
{
pageIndex: 1,
pageSize: 10,
sort: { order: '', key: '' },
query: '',
filterData: {
analysis: [ '0', '1', '2', '3' ],
threat_level_id: [ '1', '2', '3', '4' ],
}
}
EndPoint:
POST /api/v1/events/public/list
Controller:
exports.getPublicEvents = async (req, res) => {
try {
client.ping()
const { pageIndex, pageSize, sort, query, filterData } = req.body
let esQuery = {
index: 'ns_*',
body: {
query: {
bool: {
must: [
{
match_all: {},
},
],
filter: [],
},
},
from: (pageIndex - 1) * pageSize,
size: pageSize,
},
}
if (query) {
esQuery.body.query.bool.must = [
{
match: {
'Event.info': {
query: query,
fuzziness: 'AUTO',
},
},
},
]
}
if (filterData.analysis.length > 0) {
esQuery.body.query.bool.filter.push({
terms: {
'Event.analysis': filterData.analysis,
},
})
}
if (filterData.threat_level_id.length > 0) {
esQuery.body.query.bool.filter.push({
terms: {
'Event.threat_level_id': filterData.threat_level_id,
},
})
}
let esResponse = await client.search(esQuery)
let data = esResponse.hits.hits.map((hit) => hit._source)
let total = esResponse.hits.total.value
res.status(200).json({
status: 'success',
data: data,
total: total,
})
} catch (error) {
res.status(500).json({
error: 'Error connecting to Elasticsearch',
errorMessage: error.message,
})
}
}
The controller below is without filters and it works just fine.
exports.getPublicEvents = async (req, res) => {
try {
client.ping()
const { pageIndex, pageSize, sort, query } = req.body
let esQuery = {
index: 'ns_*',
body: {
query: {
match_all: {},
},
from: (pageIndex - 1) * pageSize,
size: pageSize,
},
}
if (query) {
esQuery.body.query = {
match: {
'Event.info': {
query: query,
fuzziness: 'AUTO',
},
},
}
}
let esResponse = await client.search(esQuery)
let data = esResponse.hits.hits.map((hit) => hit._source)
let total = esResponse.hits.total.value
res.status(200).json({
status: 'success',
data: data,
total: total,
})
} catch (error) {
res.status(500).json({
error: 'Error connecting to Elasticsearch',
errorMessage: error.message,
})
}
}
ElasticSearech version: 7.17.8
Result of: console.log(JSON.stringify(esQuery))
{
"index": "INDEX_NAME",
"body": {
"query": {
"bool": {
"must": [{ "match_all": {} }],
"filter": [
{ "terms": { "Event.analysis": ["0", "1", "2"] } },
{ "terms": { "Event.threat_level_id": ["1", "2", "3", "4"] } }
]
}
},
"from": 0,
"size": 10
}
}
Data in elascticsearch schema
{
"#version": "1",
"#timestamp": "2023-02-01T14:43:09.997Z",
"Event": {
"info": ".......................",
"description": ".......................",
"analysis": 0,
"threat_level_id": "4",
"created_at": 1516566351,
"uuid": "5a64f74f0e543738c12bc973322",
"updated_at": 1675262417
}
}
Index Mapping
{
"index_patterns": ["INDEX_NAME"],
"template": "TEMPLATE_NAME",
"settings": {
"number_of_replicas": 0,
"index.mapping.nested_objects.limit": 10000000
},
"mappings": {
"dynamic": false,
"properties": {
"#timestamp": {
"type": "date"
},
"Event": {
"type": "nested",
"properties": {
"date_occured": {
"type": "date"
},
"threat_level_id": {
"type": "integer"
},
"description": {
"type": "text"
},
"is_shared": {
"type": "boolean"
},
"analysis": {
"type": "integer"
},
"uuid": {
"type": "text"
},
"created_at": {
"type": "date"
},
"info": {
"type": "text"
},
"shared_with": {
"type": "nested",
"properties": {
"_id": {
"type": "text"
}
}
},
"updated_at": {
"type": "date"
},
"author": {
"type": "text"
},
"Attributes": {
"type": "nested",
"properties": {
"data": {
"type": "text"
},
"type": {
"type": "text"
},
"uuid": {
"type": "text"
},
"comment": {
"type": "text"
},
"category": {
"type": "text"
},
"value": {
"type": "text"
},
"timestamp": {
"type": "date"
}
}
},
"organisation": {
"type": "nested",
"properties": {
"name": {
"type": "text"
},
"uuid": {
"type": "text"
}
}
},
"Tags": {
"type": "nested",
"properties": {
"color": {
"type": "text"
},
"name": {
"type": "text"
}
}
},
"TLP": {
"type": "nested",
"properties": {
"color": {
"type": "text"
},
"name": {
"type": "text"
}
}
}
}
}
}
}
}
Event is a nested field, so you need to use nested queries, like this:
{
"index": "INDEX_NAME",
"body": {
"query": {
"bool": {
"must": [{ "match_all": {} }],
"filter": [
{
"nested": {
"path": "Event",
"query": {"terms": { "Event.analysis": ["0", "1", "2"] }}
}
},
{
"nested": {
"path": "Event",
"query": {"terms": { "Event.threat_level_id": ["1", "2", "3", "4"] }}
}
}
]
}
},
"from": 0,
"size": 10
}
}
In troubleshooting this problem we found that swagger.json contained incorrect case for
"type": "String"
in the generated code
"/api/FrameLookUp": {
"post": {
"tags": [
"Frame"
],
"operationId": "FrameLookup",
"consumes": [
"application/json-patch+json",
"application/json",
"text/json",
"application/*+json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "header",
"name": "Authorization",
"description": "access token",
"required": true,
"type": "String"
},
{
"in": "body",
"name": "body",
"schema": {
"$ref": "#/definitions/FrameRequest"
}
}
],
"responses": {
"200": {
"description": "Success",
"schema": {
"$ref": "#/definitions/FrameResponse"
}
}
}
}
}
}
I have the following ISchemaFilter
public class SwaggerEnumFilter : ISchemaFilter
{
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (model == null)
throw new ArgumentNullException("model");
if (context == null)
throw new ArgumentNullException("context");
if (context.Type.IsEnum)
model.Extensions.Add(
"x-ms-enum",
new OpenApiObject
{
["name"] = new OpenApiString(context.Type.Name),
["modelAsString"] = new OpenApiBoolean(false)
}
);
}
}
What could be causing this?
It turned out to be that I was using
services.AddSwaggerGen(c =>
{
c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
and inside the class I had
Schema = new OpenApiSchema() { Type = "String" },
it should have had "string" as lower case.
I'm trying to hit the REST endpoint by using AXIOS library and the response.data return the below in console.log:
Reseponse for console.log(response.data)
{
sqlQuery: "select type,subtype from wetrade_p2 where parent_id='69341269'",
message: '1 rows selected',
row: [ { column: [Array] } ]
}
But when I hit the same REST endpoint in postman and I can get the entire Response JSON as like below:
PostMan Output (Expected):
{
"sqlQuery": "select type,subtype from wetrade_p2 where parent_id='69341269'",
"message": "2 rows selected",
"row": [
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "P",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
},
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "S",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
}
]
}
I also tried to stingify the response.data and it returned below response which is not able to parse()
Getting below response in console.log when I tried to use JSON.stringify(response.data):
sqlQuery: "select type,subtype from wetrade_p2 where parent_id=69341269"
message: "2 rows selected"
row: [
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "P",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
},
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "S",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
}
]
Sample Code:
await axios[methodType](url, body, {
httpsAgent:httpsAgent,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": true
}
}).then(response => {
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(response.data);
console.log(JSON.stringify(response.data))
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(response);
}).catch(error => {
console.log(error);
});
You DO get the right data, just node.js doesn't display it in the console/stdout. You can use util.inspect() for a better formatted output. Try this:
const util = require('util');
// ...
console.log(util.inspect(response.data, { showHidden: false, depth: null }));
I am providing users with a response on an audio only device (e.g. google home), when I respond with a textToSpeech field within a simpleResponse, the speech is not read out in the simulator.
Has anyone experienced this and know how to fix?
I've tried different response types but none of them read out the textToSpeech field.
Also tried ticking/unticking end conversation toggle in Dialogflow and expectUserInput true/false when responding with JSON to no avail.
The response is currently fulfilled by a webhook which responds with JSON v2 fulfilment blob and the simulator receives the response with no errors but does not read it out.
RESPONSE -
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "Here are the 3 closest restaurants that match your criteria,"
}
}
]
}
}
}
}
REQUEST -
{
"responseId": "404f3b65-73a5-47db-9c17-0fc8b31560a5",
"queryResult": {
"queryText": "actions_intent_NEW_SURFACE",
"parameters": {},
"allRequiredParamsPresent": true,
"outputContexts": [
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/findrestaurantswithcuisineandlocation-followup",
"lifespanCount": 98,
"parameters": {
"location.original": "Shoreditch",
"cuisine.original": "international",
"cuisine": "International",
"location": {
"subadmin-area": "Shoreditch",
"subadmin-area.original": "Shoreditch",
"subadmin-area.object": {}
}
}
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_capability_account_linking"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_capability_audio_output"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/google_assistant_input_type_voice"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_capability_media_response_audio"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_intent_new_surface",
"parameters": {
"text": "no",
"NEW_SURFACE": {
"#type": "type.googleapis.com/google.actions.v2.NewSurfaceValue",
"status": "CANCELLED"
}
}
}
],
"intent": {
"name": "projects/my-project/agent/intents/0baefc9d-689c-4c33-b2b8-4e130f626de1",
"displayName": "Send restaurants to mobile"
},
"intentDetectionConfidence": 1,
"languageCode": "en-us"
},
"originalDetectIntentRequest": {
"source": "google",
"version": "2",
"payload": {
"isInSandbox": true,
"surface": {
"capabilities": [
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.MEDIA_RESPONSE_AUDIO"
},
{
"name": "actions.capability.ACCOUNT_LINKING"
}
]
},
"requestType": "SIMULATOR",
"inputs": [
{
"rawInputs": [
{
"query": "no",
"inputType": "VOICE"
}
],
"arguments": [
{
"extension": {
"#type": "type.googleapis.com/google.actions.v2.NewSurfaceValue",
"status": "CANCELLED"
},
"name": "NEW_SURFACE"
},
{
"rawText": "no",
"textValue": "no",
"name": "text"
}
],
"intent": "actions.intent.NEW_SURFACE"
}
],
"user": {
"userStorage": "{\"data\":{}}",
"lastSeen": "2019-04-12T14:31:23Z",
"locale": "en-US",
"userId": "userID"
},
"conversation": {
"conversationId": "sessionId",
"type": "ACTIVE",
"conversationToken": "[\"defaultwelcomeintent-followup\",\"findrestaurantswithcuisineandlocation-followup\",\"findrestaurantswithcuisineandlocation-followup-2\"]"
},
"availableSurfaces": [
{
"capabilities": [
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.SCREEN_OUTPUT"
},
{
"name": "actions.capability.WEB_BROWSER"
}
]
}
]
}
},
"session": "projects/my-project/agent/sessions/sessionId"
}
I expect the simulator to read out the result of textToSpeech but currently does not.
I am creating a Restful server in ExpressJs. I have integrated swagger-jsdoc. Following is the related files. Below(header.png) is how I expect my header to look like in swagger UI. But, while I open my swagger UI (http://localhost:3000/api-docs/), I am not able to see Token tags (token and Authentication) in the header.
swagger.json
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Viswa API"
},
"host": "localhost:3000",
"basePath": "/api",
"tags": [{
"name": "Customers",
"description": "API for customers in the system"
}],
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"securityDefinitions": {
"Bearer": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
},
"JWT": {
"type": "apiKey",
"name": "token",
"in": "header"
}
},
"paths": {
"/customer": {
"post": {
"tags": [
"Customers"
],
"description": "Create new customer in system",
"parameters": [{
"name": "customer",
"in": "body",
"description": "Customer that we want to create",
"schema": {
"$ref": "#/definitions/Customer"
}
}],
"produces": [
"application/json"
],
"responses": {
"201": {
"description": "New customer is created",
"schema": {
"$ref": "#/definitions/Customer"
}
}
}
}
}
},
"definitions": {
"Customer": {
"required": [
"email"
],
"properties": {
"customer_name": {
"type": "string"
},
"customer_email": {
"type": "string"
}
}
}
}
}
app.route
var apiRoutes = express.Router();
app.use('/api', apiRoutes);
// swagger definition
var swaggerUi = require('swagger-ui-express'),
swaggerDocument = require('../swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/api/v1', apiRoutes);
Current Swagger UI:
You are missing the security tag. You can define it either globally just below the securityDefinitions tag or one for each API endpoint.
Have a look at this question.
You can add a security tag
"security": [ { "Bearer": [] } ],
After adding it your path section
"paths": {
"/customer": {
"post": {
"security": [ { "Bearer": [] } ],
"tags": [
"Customers"
],
"description": "Create new customer in system",
"parameters": [{
"name": "customer",
"in": "body",
"description": "Customer that we want to create",
"schema": {
"$ref": "#/definitions/Customer"
}
}],
"produces": [
"application/json"
],
"responses": {
"201": {
"description": "New customer is created",
"schema": {
"$ref": "#/definitions/Customer"
}
}
}
}
}
},
You can define the header parameters in the path definition. like this
"paths": {
"/customer": {
parameters: [{ name: "Authorization", in: "header", type: "string", description: "auth token" }]
}
}