When I push my code to sonar, it mentioned below type of codes not cover by unit tests(Jest JS). How to remove this kind of swagger definition code from code coverage in sonar.
#ApiOperationPost({
description: "Student details",
summary: "Student details",
path: "/student",
security: {
authorization: [],
},
parameters: {},
responses: {
200: {
description: "Student details request",
model: "StudentDetailsRequest",
type: SwaggerDefinitionConstant.Response.Type.ARRAY,
},
400: { description: "Expected Parameters Missing", model: "Problem" },
401: { description: "Unauthorized", model: "Problem" },
500: { description: "Internal Server Error", model: "Problem" },
},
})
Please help me to solve this issue. Any help or workarounds are really appreciated.
Related
So I have the following scenario.
We have a specific set of custom exceptions that we need to throw from the backend (written with AWS Lambdas) so that the frontend can receive a specific response that he knows how to treat.
Our responses for the client (frontend) look like this in case of an error.
We have code, statusCode, message
{
"error": {
"code": 4004,
"statusCode": 404,
"message": "Not found"
}
}
Now, the issue is that the way we do it is by extending the Exception class in Python, so when something happens we can do raise CustomException.
It's all working fine, the only issue that we have is that AWS Cloudwatch treats this as ERRORS and so we are in a case where every single BadRequest is costing us an error in cloudwatch, which is something we do not want.
I would like to build it in such a way that I manage to throw this response to the client but the status of the HTTP request to be the actual statusCode that I put. So far, I have only managed to do something like this:
As you can see, I have the response I need, however, the statusCode for the HTTP request is 200, when in fact it should be 404.
This is how we create the endpoint in the cdk:
props.apiStack.createEndpoint("GET", "/clinics/{clinicID}/credits/stats", getCreditsStats, {
authorizationType: AuthorizationType.COGNITO,
requestParameters: {
"method.request.header.x-user-auth": true,
"method.request.path.clinicID": true
},
requestTemplateBody: `{
"httpMethod": "$context.httpMethod",
"token": "$input.params('x-user-auth')",
"clinicID": "$input.params('clinicID')"
}`,
});
And this is how the createEndpoint method looks like:
public createEndpoint(method: string, path: string, lambda: Function, props: EndpointProps): Method {
const { authorizationType, requestParameters, requestTemplateBody } = props;
const integration = new LambdaIntegration(lambda, {
proxy: false,
requestParameters: Object.keys(requestParameters || {}).reduce(
(o, key) => ({ ...o, [`${key.replace("method.", "integration.")}`]: key }),
{}
),
requestTemplates: {
"application/json": requestTemplateBody,
},
// TODO Check this param
passthroughBehavior: PassthroughBehavior.NEVER,
integrationResponses,
});
return this.api.root.resourceForPath(path).addMethod(method, integration, {
authorizationType,
authorizer: { authorizerId: this.cognitoAuthorizer.ref },
requestParameters,
methodResponses: this.methodResponses,
});
}
Also, integrationResponse looks like this:
{
selectionPattern: '.*"statusCode": 404.*',
statusCode: "404",
responseTemplates: {
"application/json": `#set ($obj = $util.parseJson($input.path('$.errorMessage')))
{"error": {
"code":$obj.error.code,
"statusCode":$obj.error.statusCode,
"message":"$obj.error.msg"}
}`,
},
responseParameters: {
"method.response.header.Content-Type": "'application/json'",
"method.response.header.Access-Control-Allow-Origin": "'*'",
"method.response.header.Access-Control-Allow-Credentials": "'true'",
"method.response.header.Access-Control-Expose-Headers": "'x-amzn-requestid'",
"method.response.header.Strict-Transport-Security": "'max-age=63072000'",
},
}
I was presuming that if I define it the way I did, it would work, and it does to some extent, we don't receive an error in Cloudwatch anymore, but the frontend cannot pickup the error because for the frontend, it's a 200 OK response.
Any help would be highly appreciated!
I bumped into this error.
Resource handler returned message: "Model validation failed (#/DefaultAction/Block/CustomResponse/ResponseCode: failed validation constraint for keyword [minimum]
)" (RequestToken: c97b2cae-821a-2be3-465a-965164d34674, HandlerErrorCode: InvalidRequest)
I am trying to make the simplest WAF for my first scratch.
const wafacl = new wafv2.CfnWebACL(this, "MyCfnWebAll",{
scope: "REGIONAL",
defaultAction: {
allow:{
customRequestHandling: {
insertHeaders: [{
name: 'name',
value: 'value',
}],
},
},
block: {
customResponse: {
responseCode: 123,
customResponseBodyKey: 'customResponseBodyKey',
responseHeaders: [{
name: 'name',
value: 'value',
}],
},
}
},
visibilityConfig:{
cloudWatchMetricsEnabled: false,
metricName: 'metricName',
sampledRequestsEnabled: false
}
});
My goal is just make the simple WAF and connect this to ALB.
Could someone help my first step?
I have an API gateway setup which sends to SQS which fires a Lambda, I am trying to pass message attributes to the SQS but when I hit the endpoint in postman I keep getting a 400 Bad Request.. what is the right way to send the attributes over a JSON POST body
here is body from postman (have tried a few options based on this link)
"message": "Message",
"MessageAttributes": {
"Name": "Name",
"Type": "String",
"Value": "my value"
}
}
Here is how API Gateway is configured
Incase someone stumbles on this later here is worked from the CDK side
let intergation = new apiGateway.CfnIntegration(this, 'Integration', {
apiId: props.httpApi.httpApiId,
payloadFormatVersion: '1.0',
integrationType: 'AWS_PROXY',
credentialsArn: apigwRole.roleArn,
integrationSubtype: 'SQS-SendMessage',
requestParameters: {
QueueUrl: sqsqueue.queueUrl,
MessageBody: '$request.body',
MessageAttributes: '$request.body.MessageAttributes'
}
})
new apiGateway.CfnRoute(this, 'Route', {
apiId: props.httpApi.httpApiId,
routeKey: apiGateway.HttpRouteKey.with('/url/foo', apiGateway.HttpMethod.POST).key,
target: `integrations/${intergation .ref}`
}).addDependsOn(intergation);
and the cloudformation
MessageBody: $request.body
MessageAttributes: $request.body.MessageAttribute
then in post man the POST body content type as application/json
{
"message": "Message",
"MessageAttributes": {
"Attributes": {
"DataType": "String",
"StringValue": "my value"
}
}
}
the lamba would log out both separate for each Record from the event body
Records: [
{
....
body: 'Message',
attributes: [Object],
messageAttributes: [Object]
}
]
}
the messageAttributes object from above:
{
Attributes: {
stringValue: 'my value',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
}
}
This is using AWS API Gateway v2 HTTP API also
I try to define my AWS Api Gateway infrastructure using Swagger/OpenAPI. Everything is working so far, however I have problems enabling the need for an API-Key for my endpoints.
My Swagger file looks like this (shortened):
---
swagger: 2.0
basePath: /dev
info:
title: My API
description: Proof of concept
schemes:
- https
securityDefinitions:
api_key:
type: apiKey
name: X-Api-Key
in: header
paths:
/example-path:
options:
consumes:
- application/json
produces:
- application/json
x-amazon-apigateway-integration:
type: mock
requestTemplates:
application/json: |
{
"statusCode" : 200
}
responses:
"default":
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Methods: "'GET,HEAD,OPTIONS'"
method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
method.response.header.Access-Control-Allow-Origin: "'*'"
responseTemplates:
application/json: |
{}
responses:
200:
description: Default response for CORS method
headers:
Access-Control-Allow-Headers:
type: "string"
Access-Control-Allow-Methods:
type: "string"
Access-Control-Allow-Origin:
type: "string"
get:
security:
- api_key: []
x-amazon-apigateway-integration:
# Further definition of the endpoint, calling Lambda etc...
Linked inside a CloudFormation template the Swagger file is processed successfully. But when I open the endpoint in the AWS Web Console, the flag for API Key Required is still false.
Any suggestions? Thanks.
Found the solution: the API key has to be named x-api-key (all lowercase).
It seems like only this way the setting is recognized during import.
To enable required API Key you need to add this "x-amazon-apigateway-api-key-source" : "HEADER" in security scheme block.
See an example:
"components" : {
"securitySchemes" : {
"api-key" : {
"type" : "apiKey",
"name" : "x-api-key",
"in" : "header",
"x-amazon-apigateway-api-key-source" : "HEADER"
}
}
}
It's an example using proxy requests.
Your JSON should be like this:
openapi3
{
"openapi": "3.0.3",
"info": {
"title": "User Portal",
"description": "API focused in User Portal.",
"version": "v1"
},
"paths": {
"users/{proxy+}": {
"options": {
"x-amazon-apigateway-integration": {
"httpMethod": "OPTIONS",
"payloadFormatVersion": "1.0",
"type": "MOCK"
}
},
"x-amazon-apigateway-any-method": {
"produces":[ "application/json"],
"parameters": [
{
"name": "proxy",
"in": "path",
"required": "true",
"type": "string"
}
],
"responses": {},
"security": [
{
"api-key": []
}
],
"x-amazon-apigateway-integration": {
"uri":"https://test.com.br/users/{proxy}",
"httpMethod":"ANY",
"type": "HTTP_PROXY"
}
}
}
},
"components" : {
"securitySchemes" : {
"api-key" : {
"type" : "apiKey",
"name" : "x-api-key",
"in" : "header",
"x-amazon-apigateway-api-key-source" : "HEADER"
}
}
}
}
In openapi2 you can add this in your yml.
swagger: 2.0
basePath: /dev
info:
title: My API
description: Proof of concept
schemes:
- https
securityDefinitions:
api_key:
type: apiKey
name: X-Api-Key
in: header
x-amazon-apigateway-api-key-source: HEADER
If you have troubles using api integration with openapi you can see this article: Working with API Gateway extensions to OpenAPI
im using Ember Data 1.13.3. and i want to convert my old JSON format to new JSONAPI format using normalizeResponse in JSONAPISerializer.
for example i have my json coming from web service like
{
user: { id: 1, name: 'wecc', accounts: [1, 2] },
accounts: [
{ id: 1, email: 'wecc#sweden.se' },
{ id: 2, email: 'wecc#greece.gr' }
]
}
now in my JSONAPISerializer how can i get the JSONAPI format out of my old json. im getting old format. but i want that format converted automatically into JSONAPI. like below one
{
data: {
id: '1',
type: 'user',
attributes: {
name: 'wecc'
},
relationships: {
accounts: {
data: [
{ id: '1', type: 'account' },
{ id: '2', type: 'account' }
]
}
}
},
included: [{
id: '1',
type: 'account',
attributes: {
email: 'wecc#sweden.se'
}
}, {
id: '2',
type: 'account',
attributes: {
email: 'wecc#greece.gr'
}
}]
}
i found some help from ember itself.
http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_internal-format-change-to-json-api
they recommand to use normalizeResponse
It won't happen automatically. If you are also in control of your REST API I'd recommend normalizing the data on the server itself. Otherwise as you suggested it will have to happen within normalizeResponse, but with custom code written to match your data format.
Another solution is to keep using the RESTSerializer for now and wait until the JSON API specification gets a bit more popular. Tools will likely be released for most server frameworks to provide standard JSON API payloads in the coming months.