Use OpenAPI specifications to build an API Gateway APIs
By following these instructions you will create an S3 bucket, API Gateway API and two Lambdas in your AWS account. Storage of files in the S3 bucket, consumption of the API Gateway endpoint and invocation of the Lambdas will result in AWS costs. It is recommended that you delete the CloudFormation for this example once you have finished experimenting with it.
Install the NPM dependencies.
npm i
Build the application.
npm run build
This will:
- Clean the output directory
- Run linting on the code
- Run NPM audit on the dependencies
- Run the TypeScript compiler
- Run the Jest unit tests
- Copy any runtime dependencies to the dist folder
You'll need a deployment bucket in order to deploy your Serverless Application Model (SAM) stack. Perform this one time task in your target AWS account.
aws cloudformation deploy \
--stack-name api-gateway-openapi-artifact-bucket \
--template-file cloudformation/artifact-bucket.yaml
Take note of the auto generated bucket name, you'll need it later when deploying.
Use the AWS CLI to package your application and copy it to the deployment bucket.
aws s3 cp openapi.yaml s3://<YOUR DEPLOYMENT BUCKET NAME GOES HERE>
aws cloudformation package \
--template-file sam.yaml \
--output-template-file sam-generated.yaml \
--s3-bucket <YOUR DEPLOYMENT BUCKET NAME GOES HERE>
aws cloudformation deploy \
--template-file sam-generated.yaml \
--stack-name api-gateway-openapi \
--capabilities CAPABILITY_IAM \
--parameter-overrides \
DeploymentBucket=<YOUR DEPLOYMENT BUCKET NAME GOES HERE>
Retrieve your API Gateway URL using the AWS Console
The following will retrieve a list of Posts
curl https://<YOUR API GATEWAY URL GOES HERE>/live/api/posts
The following will 'create' a Post
curl --header "Content-Type: application/json" \
--request POST \
--data '{ "title": "Mock Title", "description": "Mock Description", "publishedDate": "2019-06-05T10:14:02Z", "content": "Mock Content" }' \
https://<YOUR API GATEWAY URL GOES HERE>/live/api/posts
The list of Posts are hardcoded and no state is shared between the ListPostsLambda and CreatePostLambda so Posts you 'create' with the POST request will not appear in the GET request.