Following the advice of the serverless stack tutorial, my serverless app splits the API amongst multiple services, which has worked well while using REST APIs.
createNotes:
handler: create.main
events:
- http:
method: POST
path: /notes
After discovering AWS now supports simplified/cheaper/faster HTTP APIs, I was excited to give it a try in my serverless app. Simply changing http
to httpApi
and sls deploy
did the trick!
createNotes:
handler: create.main
events:
- httpApi:
method: POST
path: /notes
When splitting an API into multiple services (aka Serverless projects with their own serverless.yml), API Gateway creates custom domains for each service. The serverless-stack tutorial provides a solution to this problem when building API Gateway REST Api’s (Share an API Endpoint Between Services.
However, when utilizing API Gateway’s new HTTP API, the same solution outlined above does not work. I assume it will be addressed in the future, but the feature does not appear to exist in the Severless Framework.
In the meantime, are there workarounds or best practices to address this issue?
I went on a similar journey a month ago and after a bug was fixed, this documentation should work for what you’re looking to do: https://www.serverless.com/framework/docs/providers/aws/events/http-api#reusing-http-api-in-different-services. I hope this answers your question.
Hi @dotorg-hala, thanks for replying to this question! I put this issue aside while I worked on other things, but I’m getting back to it now.
Do you mind describing how you used the httpApi
id
field to achieve this? I’m not sure I follow from the documentation alone and could use an example.
I follow the general strategy outlined in the serverless stack demo., as I’ve been able to get this to work with API Gateways REST API. When trying to apply the same principles to HTTP APIs, I get stuck on the last part in that tutorial, which relies on the framework generated ApiGatewayRestApi
variable. Since that variable is not created when using only HTTP APIs, I’m not sure what variable I should be relying on.
I see the documentation you linked says
We may attach configured endpoints to HTTP API created externally…
Does that mean an HTTP API endpoint created outside of the Serverless Framework (e.g. directly in the AWS Console)?
Thanks!
I create my httpApi in a separate serverless service with other infrastructure. In my serverless.yml for ever service, I reference the httpApi ID in the provider section like this:
provider:
name: aws
runtime: python3.8
httpApi:
id: [the ID of your http API goes here]
You can hardcode the ID or reference via a variable or via Import a cloud formation Export.
Then under the function it self, you just need to set the method and path (and authorizer if you want)
functions:
createSomething:
handler: create_something.handler
events:
- httpApi:
method: POST
path: /create_something
authorizer:
id: [cognitoAuthorizerId]
I hope this helps.
1 Like