- How to use Amazon API Gateway and pass query string parameters
- リソースの作成
- Creating Methods
- run a test
- Pass URL query string parameters to Lambda functions
- Set path parameters and pass them in the mapping template
- Pass the request body part with a mapping template
- Velocity Template Language (VTL) used in mapping templates
- Using Lambda Proxy Integration
- Validation check of request body in curl
- Check Use of Lambda Proxy Integration to send data via POST
- Create a model of the request
- Request Verification
- Allow null in the model
- Response body of method response (method response model)
- Testing a Cognito-protected API Gateway with POSTMAN
- Related
How to use Amazon API Gateway and pass query string parameters
This section describes how to use Amazon API Gateway. On the “Create New API” screen, enter an API name and click “Create API”.
リソースの作成
The next step is to create the resource.
Enter a resource name as appropriate. This will become part of the URL.
Click “Create Resource” to create the resource.
Creating Methods
Next, create a method for that resource.
Click “Create Method” and a combo box will appear, in which “GET” is specified.
Press the checkbox to the right of “GET” to confirm. Let’s call the Lambda function from AWS Gateway.
Specify the Lambda region and a Lambda function called getgetget, which you created appropriately, and press “Save”. A message indicating that authorization is granted will appear as shown below, and then click “OK.
By the way, getgetgetget is as follows.
run a test
Now you can call Lambda from API Gateway. Let’s actually test it.
Click on “Test.”
Click “Test” on this screen and the results will be displayed on the right side.
Pass URL query string parameters to Lambda functions
Define query string parameters in API Gateway. Click on Method Request.
Click on “Add Query String.”
You will be able to enter the following, where you will type “ID”.
Click the checkbox on the right to confirm. Next, click on “Integration Request”.
Open “Body Mapping Templates” and click “Add Mapping Template.”
The Content-Type should be “application/json”. The following screen will then be displayed.
In the input field, enter the following
{ "ID": "$input.params("userid")", "LANG": "$input.params("lang")" }
ID is the value passed from API Gateway, and ID can be accessed in a Lambda function as event.ID. Let’s test this in practice, passing an object for the ID.
The Lambda function just returns event.XX. The result is as follows
Set path parameters and pass them in the mapping template
The path parameter must be set in the resource section. Specify the following in the “Create Resource” section.
The resource name is not enclosed in {}, but the resource path is enclosed in {}. You can see that a path parameter named “userid” has been created.
The path parameter can be given as $input.params(“~~~”) as well as the query string parameter.
Pass the request body part with a mapping template
The request body part is obtained in $INPUT.BODY and passed to Lambda, etc.
Velocity Template Language (VTL) used in mapping templates
Once you open the “Body Mapping Template,” there is a feature that allows you to schedule query parameters in advance using a language called VTL.
For example, suppose you have a URI to which the query string parameter ?
If the lang is not specified, the default is ja.
#if($input.params('lang') == "ja") #set($value = "ja") #elseif($input.params('lang') == "en") #set($value = "en") #else #set($value = "ja") #end { "lang":"$value" }
This eliminates the need for extra checking logic or other coding on the Lambda side.
Using Lambda Proxy Integration
Click on “Integration Request” and check the “Use Lambda Proxy Integration” box. If this is checked, the “Integrated Response” setting will not be available. Also, the return value of the Lambda function must be returned in the following format
var responseBody = { message: "query: ," + event.queryStringParameters.XX + "!", input: event }; var response = { statusCode: responseCode, headers: { "x-custom-header" : "my custom header value" }, body: JSON.stringify(responseBody) };
Note that the body part must be a string, not an object.
- The statusCode, headers, and body are required (body is a string).
Also, the query string that was accessible in event.XX must be added “event.queryStringParameters.XX” as follows.
Path parameters can be retrieved on the Lambda side by adding event.pathParameters.YY.
The request body can be obtained by event.body.
event.queryStringParameters.XX
Validation check of request body in curl
In order for curl to perform request body validation checks, you must specify Content-Type:application/json
in the header information.
Note that if you do not specify this, the curl command will not perform request body validation checks.
If you do not want to temporarily check the request body, you can disable the request body validation check as it will be application/x-www-form-urlencoded
if Content-Type is not specified.
Check Use of Lambda Proxy Integration to send data via POST
Now let’s try POST with the Use Lambda Proxy Integration checked.
To make it a POST, select POST in “Create Method” to make it a POST.
Click “Test.
Leave the query string and header empty, and set the following in the request body
{ "ID":"test", "DATA":[ { "category":"1", "type":"2" } ] }
The following.
The Lambda function simply returns the value of DATA.
exports.handler = (event, context, callback) => { let obj = JSON.parse(event.body); let responseBody = { message: obj.DATA }; let response = { statusCode: 200, headers: {}, body: JSON.stringify(responseBody) }; callback(null, response); };
The thing to keep in mind when POSTing is that even if you pass it as an object, it will be passed as a string on the Lambda side.
Therefore, you need to parse JSON.parse.
The result of the API Gateway test is as follows.
Create a model of the request
Creating a model seems to make it easy to do things like mandatory checks on queries.
It may be useful to check the requirement of POST data, but it is very difficult to write because it needs to be written in JSON Schema.
Click on “Model” above.
Click the “Create” button to display the following input screen.
The “Model Schema” field is used to describe the model. Below is an example where the ID is required.
{ "title": "タイトル", "type": "object", "properties": { "ID": { "type": "string" } }, "required":["ID"] }
Click “Create Model” to create a model. This model is then associated with a method request, specifying the API Gateway method.
Click on the body of the request and you will see “No model” as shown below.
Click “Add Model.
The content type is “application/json” and the model name is the model you just created in the pull-down menu.
If a required field is null or something, you will get an error message as shown below.
{ "message": "Invalid request body" }
※2020/01/25追記
When OpenAPI3.0 is imported into API Gateway, it automatically generates the request body (model) for method requests.
However, please note that there are cases where keywords that are valid in Open API 3.0.1 are still invalid in draft 4 of JSON Schema.
For now, the following are invalid for API Gateway because they have been added since draft 7.
キーワード | draft-04 |
---|---|
default | × |
date | × |
time | × |
Request Verification
When request validation is set to “None,” all checks on query string parameters, HTTP request headers, and request body (JSON schema model) are ignored.
Allow null in the model
“ID”: { “type”: “string” } The above description will result in an Invalid request body error if null is specified.
If you want to allow strings or nulls, you need to use an array of [“string”, “null”] as shown below.
{ "title": "title", "type": "object", "properties": { "ID": ["string", "null"] } }
Response body of method response (method response model)
Again, the response model can be specified, but unlike the request body of a method request, it will not perform validation.
Testing a Cognito-protected API Gateway with POSTMAN
Set POSTMAN Authorization Type to “No Auth”.
Since there is “Authorization” in the header, paste the authorization token into this Value. Please obtain it from console.log, etc.
Now the Cognito-protected API Gateway can also be tested from POSTMAN.
コメント