Setting response model via Serverless framework for AWS API Gateway - aws-api-gateway

I am trying to set up my AWS API Gateway via the Serverless Framework. So far it works good but no I am struggling setting the method response as a model. I got it working for the request but not for the response and I haven't found a hint in the documentation.
...
request:
passThrough: NEVER
schema:
application/json: ${file(requestModel.json)}
template:
application/json: ${file(requestMapping.template)}
response:
headers:
Content-Type: "'application/json'"
template: $input.body
...
If I include a schema in the response, it is ignored...

Related

Getting cors error when api gateway deployed using SAM template

I have developed lambda functions in node.js and trying to deploy to api gateway with proxy integration using SAM templates.
my lambda functions are returning headers as mentioned in AWS documentation
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "https://www.example.com",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
template.yaml code
GetClientFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/GetClient/
Handler: index.handler
Runtime: nodejs14.x
Events:
GetClientCustomFieldMap:
Type: Api
Properties:
RestApiId: !Ref ClientApi # this is api with authorizer configured
Path: api/Client/GetClient/{name}
Method: get
It is creating all resources which mentioned in the path like 'api', 'Client', 'GetClient' but not with Options method, also getting cors error. Tried multiple ways from stackoverflow but could not resolve it.
Followed this url as well How to enable CORS with AWS SAM
You need to configure Cors of the Api resource for the OPTIONS methods, see https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-api.html#sam-api-cors

AWS SAM local api mock support

I have been working with AWS SAM and API first project - we have our API specified as an OpenAPI with AWS API GW extensions.
For integration testing, we use local API Gateway (through sam local start-api, which works fine with integrated endpoints from SAM template.yaml.
What I cannot figure out is whether local api supports mocked endpoints. In my desperate attempts, I went straight to API GW on AWS console and created test API and put mock configuration there. This worked when tested through API GW console (I saw mocked response and everything). I deployed API and exported OpenAPI from dev stage. Then I pasted this into my OpenAPI specification and started sam local start-api.
My configuration looks like this
/accounts/{accountId}/documents:
parameters:
- $ref: '#/components/parameters/accountId'
get:
operationId: ListAccountDocuments
summary: List all account-based documents.
description: |
...
responses:
200:
description: OK
x-amazon-apigateway-integration:
type: "mock"
responses:
default:
statusCode: "200"
responseTemplates:
application/json: "{\n \"message\": \"hello\"\n}"
requestTemplates:
application/json: "{\"statusCode\": 200}"
passthroughBehavior: "when_no_match"
When I curl curl localhost:3000/accounts/1/documents then I get 403 - Missing Token, which API GW throws when there is no integration.
Does AWS local API GW support mocks? I was not able to find that answer in documentation.
Or am I doing something wrong?

Why does SwaggerHub return error 403 when I test my OpenAPI definition?

I have the following OpenAPI definition hosted on SwaggerHub:
https://app.swaggerhub.com/apis/MyFirstAPI/1.0.1-oas3
openapi: 3.0.0
servers:
- url: http://api.myfirstapi.com/
info:
version: 1.0.1-oas3
title: Equ API
paths:
/query:
get:
tags:
- developers
parameters:
- in: query
name: searchString
schema:
type: string
responses:
'200':
description: search results matching criteria
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Equity'
'400':
description: There is 400
components:
schemas:
Equity:
...
When I test the GET /query request, it returns a 403 error:
content-length: 0
date: Fri,10 Sep 2021 14:32:54 GMT
server: nginx/1.18.0 + Phusion Passenger(R) 6.0.8
status: 403 Forbidden
via: 1.1 b5d86079363e9709b4c4051d3c94ac3d.cloudfront.net (CloudFront)
x-amz-cf-id: pYbLwlrEHg5DXkGe5FkysAjSjbSDqUg7Rrhbv-Dt8Xwt8JuPRMAW3Q==
x-amz-cf-pop: DEL54-C1
x-cache: Error from cloudfront
x-powered-by: Express,Phusion Passenger(R) 6.0.8
Why does this error happen and how to fix it?
This 403 error is somewhat misleading. The actual problem here is that the target server for requests - api.myfirstapi.com - does not actually exist. The servers list is supposed to specify your real server(s).
If you are designing a new API and don't have a live server yet, you can use SwaggerHub's mock server to similate responses and test API calls.
To add a mock to your API definition:
Click the API name on the editor toolbar.
Switch to the Integrations tab and click Add New Integrations.
Select API Auto Mocking from the list and click Add.
Enter any value for Name (e.g. mock), leave other options as is, and click Create and Execute.
Close the remaining dialogs.
This creates a mock server for your API and adds it to the servers list in your API definition:
servers:
- description: SwaggerHub API Auto Mocking
url: https://virtserver.swaggerhub.com/OWNER_NAME/API_NAME/VERSION
Make sure to select this server in the API docs before you test API calls.

How to set the Accept header globally in OpenAPI 3.0?

I have a new OpenAPI setup via SwaggerHub. Is there an option to force a certain Accept header globally?
I have set up the Content-Type on the response:
openapi: 3.0.0
paths:
/test-path:
get:
responses:
'200':
description: OK
content:
application/vnd.company.v1.0.0+json:
When inserting a different Accept header via cURL request, the following out is made:
{"message":"Missing matching response for specified Accept header"}
That makes sense, since we aren't providing any response for that.
Unlike OpenAPI/Swagger 2.0, which has global consumes and produces, OpenAPI 3.0 requires that request and response media types be defined in each operation individually. There's no way to define the Content-Type or requests or responses globally.
You can, however, $ref common response definitions (such as error responses), which can reduce the repetition.
openapi: 3.0.2
...
paths:
/foo:
get:
responses:
'400':
$ref: '#/components/responses/ErrorResponse'
/bar:
get:
responses:
'400':
$ref: '#/components/responses/ErrorResponse'
components:
responses:
ErrorResponse:
description: An error occurred
content:
application/vnd.error+json:
schema:
...

Rest API Token Based Authentication Mechanism with Swagger Not Working

I am trying to make an API call with rest token based authentication from swagger. But at server side, I don't find token in the request. I tried the same API call with poster and swagger. In Poster it works fine but in swagger it doesn't.
Below is my JSON file which I am using to make API call with token:
swagger: '2.0'
info:
title: City
description: City Information
version: 1.0.0
host: '127.0.0.1:8090'
schemes:
- http
basePath: /App
produces:
- application/json
paths:
/city/list:
get:
summary: city
description:
Show cities name and its attributes.
security:
- APIAuthKey: []
responses:
'200':
description: An array of city
default:
description: Unexpected error
securityDefinitions:
APIAuthKey:
type: apiKey
in: header
name: X-AUTH-TOKEN
And this is how swagger sends request with X-AUTH-TOKEN:
But, when I use the same API call wit same parameters and X-AUTH-TOKEN in Poster, It works fine. Below, I have highlighted that how I send request with Poster:
Can anyone please suggest if I'm doing anything wrong or missing something? Why am I unable to send token with request correctly to fetch at server side in request header?