swagger node ValidationError: "body" is required - node.js

I asked another question in another thread that gave me start on Swagger POST, but here I am stuck with another problem.
Here is my parameter definitions in my config json file
"/people/postTest": {
"post": {
"summary": "post test.",
"description": "Test.",
"operationId": "postTest",
"consumes": [
"application/json"
],
"tags": [
"test post"
],
"parameters": [
{
"in":"body",
"name":"body",
"description": "body for the POST request",
"required":true,
"schema": {"$ref":"#/definitions/inBody"}
}
] }}
"definitions": {
"inBody": {
"properties": {
"RequestSystem": {
"type": "string"
}}}}
(copied it from a big file so only took a small part but there is no issues with syntax)
and I am using CURL to post my request
curl -H "Content-Type: application/json" -X POST -d '{"RequestSystem":"IVR"}' http://localhost:8016/people/postTest
and this is the validation error I am getting when I try to start my node server
**ValidationError: "body" is required**
I know I am passing "RequestSystem" parameter but I am not sure where I am making mistakes in setting up my params in my config json file's "parameters". Any help would be appreciated.

I think you need to make required=false
[
{
"in":"body",
"name":"body",
"description": "body for the POST request",
"required":false,
"schema": {"$ref":"#/definitions/inBody"}
}
]
}
}
Try this It should work.

Related

How to send email with attachment using cURL with Azure Logic App

I am trying to build a simple Logic App in Azure, that sends an email with a zip attachment using cURL from a Linux VM.
In the Logic App, without the attachment it is working fine.
But it breaks once Attachment is configured.
JSON schema, When a HTTP request is received:
{
"properties": {
"Attachments": {
"type": "array"
},
"cc": {
"type": "string"
},
"from": {
"type": "string"
},
"html": {
"type": "string"
},
"subject": {
"type": "string"
},
"to": {
"type": "string"
}
},
"type": "object"
}
Config for Outlook Send an email v2, Logic App, Azure
Commands to send email from Linux VM:
# create attachment
echo "abcd" > test.txt
zip test.zip test.txt
# curl to send json to azure logic app, with attachment
curl -vvv --request POST \
--header 'Content-Type: application/json' \
--url 'https://prod-21.southeastasia.logic.azure.com:443/workflows/xxx/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=xxx' \
--data '{"from": "xxx#outlook.com", "cc": "xxx#outlook.com, "Attachments": [{ "Content-Type": "BASE64_ENCODED_CONTENT", "Name": "test.zip" }], "to": "xxx#outlook.com", "subject": "Hello, World!", "html": "Hey, test email." }'
Error message from the Run History, Logic App, Azure
Full error from the log:
{
"status": 400,
"message": "Parameter 'Attachment Content' cannot be null or empty.\r\nclientRequestId: 40d2dc9c-549b-4608-xxxxxxxxxxxxxxx",
"error": {
"message": "Parameter 'Attachment Content' cannot be null or empty."
},
"source": "office365-sea.azconn-sea.p.azurewebsites.net"
}
Would like to know how to handle the attachment on this scenario. Any documentation would be helpful as well.
Thank you.
Would be also interested in this topic!
Did you try to use --form instead of --data? Or do you already have a solution for this?
I also tried to specify the "Attachments" property in logic apps as:
"properties": {
"Attachment": {
"contentEncoding": "base64",
"contentMediaType": "image/png",
"type": "string"
},
}
...

How to use openapi3 json specification to validate if Express application has set up correct routes?

Summary
I use orval to generate frontend code in order to fetch data from the backend. The API specification is using the openapi 3 format.
I want to be able to automatically validate if my express backend is implementing the correct endpoints by comparing the specification with the actual implementation.
Example
Let's assume that this is the specification api.json:
{
"openapi": "3.0.0",
"info": {
"version": "1.0.0",
"title": "My Service"
},
"servers": [
{
"url": "http://my.service.com/api"
}
],
"paths": {
"/my-endpoint": {
"get": {
"summary": "List all things",
"operationId": "listThings",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Thing"
}
}
}
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Thing": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
},
"Error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
}
}
}
Orval generates frontend code to fetch defined endpoints via axios and the according Typescript interfaces for request and response data.
So far so good.
Problem
My express backend does not know about the openapi specification. I need to manually create the correct express endpoints and make sure that they return the correct HTTP codes, correct response types and correct error handling.
I learned there are code generators like swagger-routes-express, but my concern with those is that they hide the endpoint definition and that it could be difficult to implement extra business logic to those endpoints. I may be wrong here, but i still didn't get how that would work in this scenario.
Desired solution
I think there are two variants that would be a great outcome:
A code generator that parses the api.json above and generates correct endpoints with proper Typescript types. It needs to be able to accept custom code in those endpoints which shouldn't be overwritten the next time the specification changes and code is regenerated.
A linter that checks the code if the correct endpoints exist and have the correct request and response types. Maybe a set of eslint rules.
Is there anything out there i could use for this?

Azure REST API for running builds or pipelines

I am trying to automate the creation of Azure Pipelines for a particular branch using their REST api.
However, I am struggling to use almost all their API's, as their documentation lacks examples.
Things like List and Get are simple enough.
However, when it comes to queuing a build:
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-6.0
POST https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=6.0
{
"parameters": <parameters>, // how do i send paramters
"definition": {
"id": 1
},
"sourceBranch": "refs/heads/feature/my-pipeline",
"sourceVersion": "d265f01aeb4e677a25725f44f20ceb3ff1d7d767"
}
I am currently struggling to send parameters.
I have tried:
Simple JSON like:
"parameters": {
"appId": "bab",
"platform": "android",
"isDemo": true
}
and stringify version of JSON like:
"parameters": "{\"appId\": \"bab\",\"platform\": \"android\",\"isDemo\": true}"
but none seems to work.
It keeps giving me the error:
{
"$id": "1",
"customProperties": {
"ValidationResults": [
{
"result": "error",
"message": "A value for the 'appId' parameter must be provided."
},
{
"result": "error",
"message": "A value for the 'platform' parameter must be provided."
},
{
"result": "error",
"message": "A value for the 'isDemo' parameter must be provided."
}
]
},
"innerException": null,
"message": "Could not queue the build because there were validation errors or warnings.",
"typeName": "Microsoft.TeamFoundation.Build.WebApi.BuildRequestValidationFailedException, Microsoft.TeamFoundation.Build2.WebApi",
"typeKey": "BuildRequestValidationFailedException",
"errorCode": 0,
"eventId": 3000
}
The docs is very unclear in how to send this data: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-6.1#propertiescollection
Thank you very much for you help.
I believe you cannot pass runtime parameters trough the Queue API. Instead, use Runs API
With that, your request body (use Content-type: application/json) should look something similar to this:
{
"resources": {
"repositories": {
"self": {
"refName": "refs/heads/feature/my-pipeline"
}
}
},
"templateParameters": {
"appId": "bab"
"platform": "android"
"isDemo": true
}
}
I just realized that in the api-version=6.0 you can also send templateParameters on the Queue Service:
POST https://dev.azure.com/{organization}/{project}/_apis/build/builds?sourceBuildId={BUILD_BUILDID}&api-version=6.0
{
"templateParameters": { "doReleaseBuild": "True" },
"definition": {
"id": 1
},
"sourceBranch": "refs/heads/feature/my-pipeline",
"sourceVersion": "d265f01aeb4e677a25725f44f20ceb3ff1d7d767"
}

Dialogflow Webhooks: What is a webhookStatus code 14 mean?

My Dialogflow project is not making proper webhook calls. I ran the curl command, given to you while testing, in command prompt.
curl -H "Content-Type: application/json; charset=utf-8" -H "Authorization: Bearer ya29.c.Ko8BvQcQFJJgEzKprtZn9kWStTWE5trMyYN8_oilT_4LInyASeCGiBcrrSepTvrjomVCZKSaFF_RaCYoC_yBU0LWM8ODzRlliAHQv1C97veQuxNjq_aeWLEN361drz6Rk_WEn7hl52DRN32ee4xmV97rW8nqBVFsbPykXdkjj83iKWjwKv9FKVhNJNOfMaejMH4" -d "{\"queryInput\":{\"text\":{\"text\":\"run\",\"languageCode\":\"en\"}},\"queryParams\":{\"timeZone\":\"America/New_York\"}}" "https://dialogflow.googleapis.com/v2/projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb:detectIntent"
The response I got back was:
{
"responseId": "5eea8256-8771-4db1-8b51-2c82e31c7bf4-2e39b744",
"queryResult": {
"queryText": "run",
"parameters": {},
"allRequiredParamsPresent": true,
"fulfillmentText": "Error: Speed test has not been called properly",
"fulfillmentMessages": [
{
"text": {
"text": [
"Error: Speed test has not been called properly"
]
}
}
],
"outputContexts": [
{
"name": "projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb/contexts/location",
"lifespanCount": 5
},
{
"name": "projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb/contexts/weathercontext-followup",
"lifespanCount": 2
}
],
"intent": {
"name": "projects/weathersample-ifjqjr/agent/intents/98199125-8fc6-466f-98b6-7648e14b06e7",
"displayName": "runSpeedTest"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 2439
},
"languageCode": "en"
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
}
At the bottom of this response there is a "webhookStatus" object with an unavailable error and code of 14. Does anyone know what that code means?
Webhook is basically HTTP callback which will be triggered when the web-hook enabled intents are matched. Code:14 UNAVAILABLE means that it is looking for a handling function mapped to "runSpeedTest" intent which is not present in the web-hook provided. You can test it in Fulfilment->Inline Editor before deploying it externally.

Swagger UI seems to not handle optional keys with POST json body

Packages :
hapi-swagger: 9.0.1
joi: 13.0.2
Context :
I use the swagger-ui with a swagger.json file generated by hapi-swagger.
I use for hapi-swagger the jsonEditor option set to true.
Which means that i don't enter myself the body in a single text area but i use directly the generated inputs of the UI.
Issue :
Only the key "name" is required in the payload, the other ones are optional by default if i refer to the Joi doc.
Actually the Swagger-UI sends :
curl -X POST
--header 'Content-Type: application/json'
--header 'Accept: application/json'
-d '{
"name":"fzef",
"idsUser": [],
"idsUsergroup":[]
}'
Instead i want that the Swagger-UI to send a request like :
curl -X POST
--header 'Content-Type: application/json'
--header 'Accept: application/json'
-d '{
"name":"fzef",
}'
Swagger UI
Joi Schema
Joi.object().keys({
request: Joi.object().keys({
name: Joi.string().required(),
idsUser: Joi.array().items(Joi.string()),
idsUsergroup: Joi.array().items(Joi.string()),
}),
}),
});
Swagger.json
...
"paths": {
"/addCompany": {
"post": {
"operationId": "postAddcompany",
"parameters": [{
"type": "string",
"default": "1",
"pattern": "/^v[0-9]+$/",
"name": "apiVersion",
"in": "path",
"required": true
},
{
"in": "body",
"name": "body",
"schema": {
"$ref": "#/definitions/Model 208"
}
}
],
"tags": ["api", "CompanyCommandsAPIPart"],
"responses": {
"default": {
"schema": {
"type": "string"
},
"description": "Successful"
},
}
}
}
}
"definitions": {
...
"Model 208": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"idsUser": {
"$ref": "#/definitions/Model 13",
"type": "array",
"x-alternatives": [{
"$ref": "#/x-alt-definitions/idsFunctionality",
"type": "array"
}, {
"type": "string"
}]
},
"idsUsergroup": {
"$ref": "#/definitions/Model 13",
"type": "array",
"x-alternatives": [{
"$ref": "#/x-alt-definitions/idsFunctionality",
"type": "array"
}, {
"type": "string"
}]
},
},
"required": ["name"]
},
...
}
What can i do to get this request body ?
Do i need to precise a joi method in order that the hapi-swagger parser add a parameter like 'optional' to the swagger.json ?
I found the same issue for the query of a GET method but found no solution:
https://github.com/swagger-api/swagger-editor/issues/684
The JSON Editor component provides the "Properties" and "Edit JSON" buttons to customize the JSON payload, as you can in the component demo here: http://jeremydorn.com/json-editor/. However, Swagger UI 2.x (the version used by hapi-swagger at the time of writing) initializes the JSON Editor with disable_properties: true and disable_edit_json: true so that these buttons are hidden, and the UI does not expose any configuration options to change the JSON Editor options. There is an open issue in the hapi-editor repository on GitHub: https://github.com/glennjones/hapi-swagger/issues/332.
A possible workaround is to tweak the Swagger UI code. Assuming your Swagger UI's index.html uses unminified swagger-ui.js, find the following lines in <hapi-swagger>/public/swaggerui/swagger-ui.js:
disable_properties:true,
disable_edit_json:true,
and replace them with:
disable_properties:false,
disable_edit_json:false,
Now the JSON Editor will have the "Object Properties" button. Click this button to select the properties to be displayed in the form editor and included in the request body. Unselected properties will not be sent in the request body.

Resources