在本地堆栈中创建API网关 [英] Create API gateway in localstack

查看:84
本文介绍了在本地堆栈中创建API网关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够设置localstack( https://github.com/atlassian/localstack )并在其中创建lambda函数(使用create-function ...命令).但是,我找不到在本地堆栈中创建APIGateway的方法,以便可以使用它来调用lambda函数. 基本上,我需要一个APIGateway(及其arn),以便可以使用该lambda函数进行调用.

I was able to setup localstack (https://github.com/atlassian/localstack) and also create lambda function in it (using create-function ... command). However, I couldnt find a way to create an APIGateway in localstack so that the lambda function can be called using it. Basically, I need an APIGateway(and its arn), so that using that the lambda function can be called.

推荐答案

每个CLI创建与API网关一起创建NodeJS Lambda的演练:

首先,我们创建一个简单的NodeJS Lambda:

First we create a simple NodeJS Lambda:

const apiTestHandler = (payload, context, callback) => {
console.log(`Function apiTestHandler called with payload ${JSON.stringify(payload)}`);
callback(null, {
    statusCode: 201,
    body: JSON.stringify({
        somethingId: payload.pathParameters.somethingId
    }),
    headers: {
        "X-Click-Header": "abc"
    }
}); 
}
module.exports = {
    apiTestHandler,
}

将其放入名为apiTestHandler.zip的zip文件中,并将其上传到localstack:

Put that into a zip File called apiTestHandler.zip and upload it to localstack:

aws lambda create-function \
--region us-east-1 \
--function-name api-test-handler \
--runtime nodejs6.10 \
--handler index.apiTestHandler \
--memory-size 128 \
--zip-file fileb://apiTestHandler.zip \
--role arn:aws:iam::123456:role/role-name --endpoint-url=http://localhost:4574

现在我们可以创建Rest-Api:

Now we can create our Rest-Api:

aws apigateway create-rest-api --region us-east-1 --name 'API Test' --endpoint-url=http://localhost:4567

这将给出以下响应:

{
"name": "API Test",
"id": "487109A-Z548",
"createdDate": 1518081479
}

有了我们到达的ID,我们可以要求其父ID:

With the ID we got here, we can ask for its parent-ID:

aws apigateway get-resources --region us-east-1 --rest-api-id 487109A-Z548 --endpoint-url=http://localhost:4567

响应:

{
"items": [
    {
        "path": "/",
        "id": "0270A-Z23550",
        "resourceMethods": {
            "GET": {}
        }
    }
]
}

现在,我们拥有创建资源及其路径的一切:

Now we have everything to create our resource together with its path:

aws apigateway create-resource \
--region us-east-1 \
--rest-api-id 487109A-Z548 \
--parent-id 0270A-Z23550 \
--path-part "{somethingId}" --endpoint-url=http://localhost:4567

响应:

{
"resourceMethods": {
    "GET": {}
},
"pathPart": "{somethingId}",
"parentId": "0270A-Z23550",
"path": "/{somethingId}",
"id": "0662807180"
}

我们在这里获得的ID是创建链接的GET方法所必需的:

The ID we got here is needed to create our linked GET Method:

aws apigateway put-method \
 --region us-east-1 \
 --rest-api-id 487109A-Z548 \
 --resource-id 0662807180 \
 --http-method GET \
 --request-parameters "method.request.path.somethingId=true" \
 --authorization-type "NONE" \
--endpoint-url=http://localhost:4567

我们快到了-最后要做的事情之一就是与已经上传的lambda建立我们的集成:

We are almost there - one of the last things to do is to create our integration with the already uploaded lambda:

aws apigateway put-integration \
 --region us-east-1 \
 --rest-api-id 487109A-Z548 \
 --resource-id 0662807180 \
 --http-method GET \
 --type AWS_PROXY \
 --integration-http-method POST \
 --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:api-test-handler/invocations \
 --passthrough-behavior WHEN_NO_MATCH \
 --endpoint-url=http://localhost:4567

最后但并非最不重要:将我们的API部署到所需阶段:

Last but not least: Deploy our API to our desired stage:

aws apigateway create-deployment \
 --region us-east-1 \
 --rest-api-id 487109A-Z548 \
 --stage-name test \
 --endpoint-url=http://localhost:4567

现在我们可以对其进行测试:

Now we can test it:

curl http://localhost:4567/restapis/487109A-Z548/test/_user_request_/HowMuchIsTheFish

响应:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100    34  100    34    0     0      9      0  0:00:03  0:00:03 --:--:--     9
{"somethingId":"HowMuchIsTheFish"}

我希望这会有所帮助.

提示1 :为了便于使用,我建议安装AWSCLI Local( https://github.com/localstack/awscli-local )-使用此工具,您可以使用命令"awslocal",而不必为每个命令键入"--endpoint-url = ..."

Hint 1: For easier use I recommend to install AWSCLI Local ( https://github.com/localstack/awscli-local ) - with this tool you can use the command "awslocal" and don't have to type "--endpoint-url= ..." for each command

使用无服务器框架和Localstack的演练:

您还可以使用无服务器框架( https://serverless.com/).

You can also use the Serverless Framework (https://serverless.com/).

首先通过npm安装它:

First install it via npm:

npm install serverless -g

现在,您可以基于nodejs-aws模板创建示例应用程序:

Now you can create a sample application based on a nodejs-aws template:

serverless create --template aws-nodejs

为了拥有HTTP端点,您必须编辑serverless.yml并添加相应的事件:

In order to have an HTTP endpoint, you have to edit the serverless.yml and add the corresponding event :

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: ping
          method: get

为了对您的localstack安装运行此命令,您必须使用serverless-localstack插件( https://github.com/temyers/serverless-localstack ):

In order to run this against your localstack installation you have to use the serverless-localstack plugin ( https://github.com/temyers/serverless-localstack):

npm install serverless-localstack

现在,您必须再次编辑serverless.yml,添加插件并调整端点.在我的情况下,localstack在Docker工具箱中运行,因此它的IP为192.168.99.100-您可能必须将其更改为localhost,具体取决于您的用途:

Now you have to edit your serverless.yml again, add the plugin and adjust your endpoints. In my case localstack is running inside the Docker toolbox, so it's IP is 192.168.99.100 - you may have to change this to localhost, depending on your use:

plugins:
 - serverless-localstack
custom:
  localstack:
    debug: true
    stages:
      - local
      - dev
    host: http://192.168.99.100
    endpoints:
      S3: http://192.168.99.100:4572
      DynamoDB: http://192.168.99.100:4570
      CloudFormation: http://192.168.99.100:4581
      Elasticsearch: http://192.168.99.100:4571
      ES: http://192.168.99.100:4578
      SNS: http://192.168.99.100:4575
      SQS: http://192.168.99.100:4576
      Lambda: http://192.168.99.100:4574
      Kinesis: http://192.168.99.100:4568

现在您可以尝试部署它:

Now you can try to deploy it:

serverless deploy --verbose --stage local

这将创建一个S3存储桶,上传您的lambda并创建一个cloudformation堆栈.但是,与AWS相比,由于localstack的某些不一致,该过程将失败.不过请不要失望,创建的cloudformation模板可以正常工作,您只需要一个额外的请求就可以了:

This will create an S3 bucket, upload your lambda and create a cloudformation stack. However, the process will fail due to some inconsistencies of localstack when compared against AWS. Don't be dismayed though, the created cloudformation template works fine and you just need an additional request and you are done:

awslocal cloudformation update-stack --template-body file://.serverless/cloudformation-template-update-stack.json --stack-name aws-nodejs-local

现在,您的lambda已部署并可以进行测试:

Now your lambda is deployed and can be tested:

curl http://192.168.99.100:4567/restapis/75A-Z278430A-Z/local/_user_request_/ping

响应:

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current Dload  Upload   Total   Spent    Left  Speed
100   364  100   364    0     0    111      0  0:00:03  0:00:03 --:--:--   111
{"message":"Go Serverless v1.0! Your function executed successfully!","input":{"body":null,"headers":{"host":"192.168.99.100:4567","accept":"*/*","user-agent":"curl/7.49.1"},"resource":"/restapis/75A-Z278430A-Z/local/_user_request_/ping","queryStringParameters":{},"httpMethod":"GET","stageVariables":{},"path":"/ping","pathParameters":{},"isBase64Encoded":false}}

希望这会有所帮助.

这篇关于在本地堆栈中创建API网关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆