YAML Exception - Cannot read an implicit mapping pair - aws-api-gateway

Exception while doing replaceAll
Y A M L Exception
can not read an implicit mapping pair; a colon is missed in "/home/serverless.yml" at line 144, column 99: ... ($input.body).replaceAll("\\'","'")"}'
Section of serverless.yml , which throws error
request:
template:
application/json: '{"body": "$util.escapeJavaScript($input.body).replaceAll("\\'","'")"}'
application/xml: '{"body": "$util.escapeJavaScript($input.body).replaceAll("\\'","'")"}'
text/xml: '{"body": "$util.escapeJavaScript($input.body).replaceAll("\\'","'")"}'
response:
statusCodes:
200:
pattern: ''
template:
application/xml: '#set ($bodyObj = $util.parseJson($input.body)) $bodyObj'
400:
pattern: '400'
headers:
Content-Type: "'application/xml'"

This:
template:[enter image description here][1]
application/json: '{"body": "$util.escapeJavaScript($input.body).replaceAll("\\'","'")"}'
is invalid YAML for various reasons.
Your template:[enter image description here][1] is a scalar and then on the second line you start a mapping. Scalars are always leaf nodes in the YAML datastructure. Not sure what you actually want to do there.
In
'{"body": "$util.escapeJavaScript($input.body).replaceAll("\\'","'")"}'
you should escape the single quotes withing the scalar:
'{"body": "$util.escapeJavaScript($input.body).replaceAll("\\''","''")"}'

Related

How to remove JSON text (including CRLF's) inside delimited records in Powershell

Have a strange issue where I need to remove JSON text in a tilde delimited file (having the JSON breaks the import due to CRLF at the end of each line of the JSON). Example line:
Test Plan Work~Response Status: BadRequest Bad Request,Response Content: {
"trace": "0HM5285F2",
"errors": [
{
"code": "server_error",
"message": "Couldn't access service ",
"moreInfoUrl": null,
"target": {
"type": null,
"name": null
}
}
]
},Request: https://www.test.com Headers: Accept: application/json
SubscriberId:
~87c5de00-5906-4d2d-b65f-4asdfsdfsdfa29~3/17/2020 1:54:08 PM
or ones like these that don't have JSON but still have the same pattern I need:
Test Plan Pay Work~Response Status: InternalServerError Internal Server Error,Response Content: Error,Request: https://api.test.com Headers: Accept: application/json
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5c
SubscriberId: eb7aee
~9d05b16e-e57b-44be-b028-b6ddsdfsdf62a5~1/20/2021 7:07:53 PM
Need both of these types of CSV text to be in the format:
Test Plan Work~Response Status: BadRequest Bad Request~87c5de00-5906-4d2d-b65f-4asdfsdfsdfa29~3/17/2020 1:54:08 PM
The JSON (including the CRLF's at the end of each line of the JSON) are breaking the import of the data into Powershell. Any help or insight would be appreciated!
PowerShell (or rather, .NET) has two perculiar features in its regex engine that might be perfect for this use case - balancing groups and conditionals!
Balancing groups is a complicated feature to fully explain, but it essentially allows us to "keep count" of occurrences of specific named subexpressions in a regex pattern, and looks like this when applied:
PS ~> $string = 'Here is text { but wait { it has } nested { blocks }} here is more text'
PS ~> $string -replace '\{(?>\{(?<depth>)|[^{}]+|\}(?<-depth>))*(?(depth)(?!))\}'
Here is text here is more text
Let's break down the regex pattern:
\{ # match literal '{'
(?> # begin atomic group*
\{(?<depth>) # match literal '{' and increment counter
| [^{}]+ # OR match any sequence of characters that are NOT '{' or '}'
| \}(?<-depth>) # OR match literal '}' and decrement counter
)* # end atomic group, whole group should match 0 or more times
(? # begin conditional group*
(depth)(?!) # if the 'depth' counter > 0, then FAIL!
) # end conditional group
\} # match literal '}' (corresponding to the initial '{')
*) The (?>...) atomic grouping prevents backtracking - a safeguard against accidentally counting anything more than once.
For the CRLF characters in the remaining fields, we can prefix the pattern with (?s) - this makes the regex engine include new lines when matching the . "any" metacharacter, up until we reach the position just before ~87c5...:
(?s),Response Content:\s*\{(?>\{(?<depth>)|[^{}]+|\}(?<-depth>))*(?(depth)(?!))\}.*?(?=~)
Or we can, perhaps more accurately, describe the fields following the JSON as repeating pairs of , and "not ,":
,Response Content:\s*(?:\{(?>\{(?<depth>)|[^{}]+|\}(?<-depth>))*(?(depth)(?!))\})?\s*(?:,[^,]+?)*(?=~)
Let's give it a try against your multi-line input string:
$string = #'
Test Plan Work~Response Status: BadRequest Bad Request,Response Content: {
"trace": "0HM5285F2",
"errors": [
{
"code": "server_error",
"message": "Couldn't access service ",
"moreInfoUrl": null,
"target": {
"type": null,
"name": null
}
}
]
},Request: https://www.test.com Headers: Accept: application/json
SubscriberId:
~87c5de00-5906-4d2d-b65f-4asdfsdfsdfa29~3/17/2020 1:54:08 PM
'#
$string -replace ',Response Content:\s*(?:\{(?>\{(?<depth>)|[^{}]+|\}(?<-depth>))*(?(depth)(?!))\})?\s*(?:,[^,]+?)*(?=~)'
Output:
Test Plan Work~Response Status: BadRequest Bad Request~87c5de00-5906-4d2d-b65f-4asdfsdfsdfa29~3/17/2020 1:54:08 PM

Cannot pass dynamic query parameters when using `express-openapi-validator`

The idea is taken from here stack-overflow
After adding a parameter that is supposed do allow dynamic query parameters, it gives error.
Query Example:
/pets:
get:
description: |
Returns all pets
operationId: findPets
parameters:
- name: params
in: query
required: false
schema:
type: object
# If the parameter values are of specific type, e.g. string:
# additionalProperties:
# type: string
# If the parameter values can be of different types
# (e.g. string, number, boolean, ...)
additionalProperties: true
# `style: form` and `explode: true` is the default serialization method
# for query parameters, so these keywords can be omitted
style: form
explode: true
responses:
'200':
description: pet response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Executing a query, returns
{"message":"Cannot convert undefined or null to object"}
To Reproduce
Clone this repository
run npm install
run npm start
run curl http://localhost:3000/v1/pets\?type\=dog\&limit\=10\&test\=query
Expected behavior
It must allow all the query strings
This was the bug in the express-openapi-validator package.
It is now fixed in v4.4.2
To test out the functionality, see this example project

How to implement an empty path in YAML file

I am trying to implement the below calls:
POST https://host/sessions
DELETE https://host/sessions/{session_id}
The POST call is to establish a session, the DELETE call is to log out an established session.
So, in the YAML file, how to have an empty base path? It's currently a slash in the YAML file as it's a required filed, but the slash is redundant. Any idea? Thanks.
swagger: '2.0'
info:
version: '0.0.1'
title: authenticate
#description: To be provided
# #termsOfService:To be provided
contact:
name: test
basePath: /sessions
paths:
/:
post:
summary: eatablish a session
description: sessions is a collection.This POST creates a new session in the sessions collection and the name of the session returned by this command is the session token.
consumes:
- "application/json"
parameters:
- in: header
name: user_name
type: string
required: true
- in: header
name: password
type: string
required: true
responses:
200:
description: establish a session successfully
400:
$ref: "#/responses/BadRequest"
500:
description: unexpected error
schema:
$ref: '#/definitions/errorModel'
/{session_id}:
delete:
summary: log out
description: use sessionid to log out an established session.
produces:
- application/json
parameters:
- in: path
name: session_id
type: string
required: true
responses:
200:
description: log out a session successfully
400:
$ref: "#/responses/BadRequest"
500:
description: unexpected error
schema:
$ref: '#/definitions/errorModel'
Swagger defines
A relative path to an individual endpoint. The field name MUST begin with a forward slash (/).
Therefore, the slash is required and you can't have an empty path.

Openapi3 and CSV response (for Dredd)

I test my Api with DREDD against it's specification (written in Openapi3 considering, painfull limitations of Support by Dredd considered). No I have one endpoint, which produces CSV-data if the Accept-header is set so.
'/my-endpoint':
summary: ...
description: ...
get:
# parameters:
# -
# in: header
# name: Accept
# description: "Response format: application/json or text/csv"
# example: "text/csv"
responses:
'200':
description: ...
content:
text/csv:
schema:
type: string
example:
summary: 'csv table'
value: 'cell1, cell2'
When I run the test with Dredd the test fails with
expected:
headers:
body:
[
{
"key": "summary",
"value": "csv table"
},
{
"key": "value",
"value": "cell1, cell2"
}
]
statusCode: 200
Clearly there is something misunderstood and Dredd expects still JSON. Also the API is not told to produce the CSV Version. If I commit in the Accept header in the code abvoe I get the very same result - the expecetd result above and as actual result the JSON version of the my-endpoint-data and also ad warning:
warn: API description parser warning in .../tmp/transformed.specs.yml: 'Parameter Object' 'name' in location 'header' should not be 'Accept', 'Content-Type' or 'Authorization'
I read here and here: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers, use the corresponding OpenAPI keywords - but what are they? According to this and this page it seems to be enough to specify a response of the given type but that is clearly not enough to tell Dredd to produce such a header.
You got an error because the value of the example key is meant to be a literal example value. So in your case it's treated as an object with the summary and value properties.
Change your definition to:
content:
text/csv:
schema:
type: string
example: 'cell1, cell2'
Or if you want to provide a summary/description for an example, use examples instead:
content:
text/csv:
schema:
type: string
examples:
csv table:
summary: A CSV table with 2 cells
value: 'cell1, cell2'

REST API - Swagger - Don't understand why "Not a valid parameter definition"

I face issue with my swagger file :
swagger: '2.0'
paths:
/currencies:
get:
responses:
'200':
description: ''
summary: 'list currencies summary'
x-auth-type: None
x-throttling-tier: Unlimited
produces:
- application/json
description: 'list currencies description'
'/currencies/{currencieId}':
get:
responses:
'200':
description: ''
description: 'Single currency description'
parameters:
- name: currencieId
in: path
allowMultiple: false
required: true
type: string
description: 'paramter description'
summary: 'Single currency'
x-auth-type: None
x-throttling-tier: Unlimited
produces:
- application/json
info:
title: MDM
version: v1
Here is my issue :
✖ Swagger Error
Not a valid parameter definition
Jump to line 20
Details
Object
code: "ONE_OF_MISSING"
params: Array [0]
message: "Not a valid parameter definition"
path: Array [5]
0: "paths"
1: "/currencies/{currencieId}"
2: "get"
3: "parameters"
4: "0"
schemaId: "http://swagger.io/v2/schema.json#"
inner: Array [2]
level: 900
type: "Swagger Error"
description: "Not a valid parameter definition"
lineNumber: 20
Issue in swagger editor
I am a bit lost with that ....
Thanks for your help.
Julien
Remove allowMultiple: false from the definition of the currencieId parameter. That eliminates the error.
The allowMultiple keyword does not exist in the OpenAPI (fka Swagger) Specification 2.0. It was used in v1.2, but in 2.0 it was replaced with type: array and collectionFormat.
allowMultiple: false is not correct