Example app to be deployed to AWS as an API Gateway / Lambda Stack

Overview

Disclaimer

I won't answer issues or emails regarding the project anymore.

The project is old and not maintained anymore. I'm not sure if it still works this way, but maybe it can still serve as a starting point for your exploration.

fastapi-aws-lambda-example

for a detailed guide on how to deploy a fastapi application with AWS API Gateway and AWS Lambda check this

Comments
  • Unable to sam build

    Unable to sam build

    Hi,

    first of all thank you for your tutorial which is the only one dealing about fastapi and serverless out there.

    I'm having problem at the step: Stage: Build the deployment package

    When I build, I get the following error:

    Final incompatible: {pydantic==1.2(wheel), websockets==8.1(wheel), cryptography==2.8(wheel), uvloop==0.14.0(wheel)}
    Final missing wheels: {uvloop==0.14.0(wheel)}
    PythonPipBuilder:ResolveDependencies failed
    Traceback (most recent call last):
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/actions.py", line 42, in execute
        requirements_path=self.manifest_path,
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/packager.py", line 137, in build_dependencies
        self._dependency_builder.build_site_packages(requirements_path, artifacts_dir_path, scratch_dir_path)
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/packager.py", line 201, in build_site_packages
        raise MissingDependencyError(packages_without_wheels)
    aws_lambda_builders.workflows.python_pip.packager.MissingDependencyError: {uvloop==0.14.0(wheel)}
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflow.py", line 269, in run
        action.execute()
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/actions.py", line 45, in execute
        raise ActionFailedError(str(ex))
    aws_lambda_builders.actions.ActionFailedError: {uvloop==0.14.0(wheel)}
    Builder workflow failed
    Traceback (most recent call last):
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/actions.py", line 42, in execute
        requirements_path=self.manifest_path,
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/packager.py", line 137, in build_dependencies
        self._dependency_builder.build_site_packages(requirements_path, artifacts_dir_path, scratch_dir_path)
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/packager.py", line 201, in build_site_packages
        raise MissingDependencyError(packages_without_wheels)
    aws_lambda_builders.workflows.python_pip.packager.MissingDependencyError: {uvloop==0.14.0(wheel)}
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflow.py", line 269, in run
        action.execute()
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflows/python_pip/actions.py", line 45, in execute
        raise ActionFailedError(str(ex))
    aws_lambda_builders.actions.ActionFailedError: {uvloop==0.14.0(wheel)}
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/__main__.py", line 126, in main
        mode=params.get("mode", None),
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/builder.py", line 125, in build
        return workflow.run()
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflow.py", line 76, in wrapper
        func(self, *args, **kwargs)
      File "/var/lang/lib/python3.7/site-packages/aws_lambda_builders/workflow.py", line 276, in run
        raise WorkflowFailedError(workflow_name=self.NAME, action_name=action.NAME, reason=str(ex))
    aws_lambda_builders.exceptions.WorkflowFailedError: PythonPipBuilder:ResolveDependencies - {uvloop==0.14.0(wheel)}
    Build inside container returned response {"jsonrpc": "2.0", "id": 1, "error": {"code": 400, "message": "PythonPipBuilder:ResolveDependencies - {uvloop==0.14.0(wheel)}"}}
    
    Build Failed
    Sending Telemetry: {'metrics': [{'commandRun': {'awsProfileProvided': False, 'debugFlagProvided': True, 'region': '', 'commandName': 'sam build', 'duration': 123589, 'exitReason': 'BuildError', 'exitCode': 1, 'requestId': 'd943b1f2-73e0-42d3-b8fb-2e94d5436dd4', 'installationId': 'acc6ee82-60bf-4a06-a81c-405c230a0da1', 'sessionId': '3600cf82-fe9d-4961-9a97-7ad8a856986b', 'executionEnvironment': 'CLI', 'pyversion': '3.7.6', 'samcliVersion': '0.41.0'}}]}
    HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read timed out. (read timeout=0.1)
    Error: PythonPipBuilder:ResolveDependencies - {uvloop==0.14.0(wheel)}
    

    I've tried to look online and nothing very significant.

    Do you have any idea what could be wrong ?

    Thanks

    help wanted 
    opened by yeyeric 5
  • Accessing PostgreSQL credentials in project

    Accessing PostgreSQL credentials in project

    In my customized version of your project, calls to my API will return records from a PostgreSQL RDS database. Do you know the best way to access the database connection string without hard-coding them into my project?

    I was thinking that maybe the simplest way is creating encrypted environment variables for the lambda function, but I also am not sure how to implement this following the style of your project.

    Thank you for your help.

    opened by KurtKline 4
  • unable to access to /docs

    unable to access to /docs

    Hi (again),

    I've managed to deploy properly your app (I was trying mine at first and I successfully deployed it, but I was unable to access the /docs page, so decided to go with yours).

    With your app, cloning your project, and building, packaging and deploying it, I have an error when access the /docs page, is that expected ? Pb api

    FYI that's the same error I also have when accessing my project, even if I put maximum RAM it doesn't change anything.

    Looking at the log doesn't give anything relevant (or maybe I didn't look at the proper place ?) START RequestId: 8681588b-b3c5-4827-a94a-0e3b4cbddaf0 Version: $LATEST END RequestId: 8681588b-b3c5-4827-a94a-0e3b4cbddaf0 REPORT RequestId: 8681588b-b3c5-4827-a94a-0e3b4cbddaf0 Duration: 3.82 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 85 MB Init Duration: 562.30 ms

    I can only see lines like this

    Would you have any idea ?

    Thanks

    Edit: just tried to access the /ping, and it works ! Why isn't it the case with /docs ?

    opened by yeyeric 3
  • /docs and /redoc not loading when deployed on AWS

    /docs and /redoc not loading when deployed on AWS

    First of all, thank you very much for your tutorial. I was able to deploy your example project to AWS, and when I use the URL with /prod/ping I get the expected result:

    { ping: "pong!" }

    However, when I try to use the URL with /prod/docs or prod/redoc I get a "Failed to load API definition" error.

    image

    Any ideas why this may be happening?

    opened by KurtKline 2
  • aws sam local start-api

    aws sam local start-api

    Wondering if you had success running start-api - I am using ptvsd

    ❯ sam local start-api

    Mounting FastapiExampleLambda at http://127.0.0.1:3000/{proxy+} [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
    You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
    2020-08-22 15:47:14  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
    Invoking example_app.main.handler (python3.8)
    Failed to download a new amazon/aws-sam-cli-emulation-image-python3.8:rapid-1.0.0 image. Invoking with the already downloaded image.
    Mounting /Users/dwbelliston/code/learn/fastapi-aws-lambda-example/.aws-sam/build/FastapiExampleLambda as /var/task:ro,delegated inside runtime container
    START RequestId: 19059eac-f60f-13d2-72c7-e958e53e642e Version: $LATEST
    [INFO]	2020-08-22T21:47:22.342Z	19059eac-f60f-13d2-72c7-e958e53e642e	Waiting for application startup.
    [INFO]	2020-08-22T21:47:22.342Z	19059eac-f60f-13d2-72c7-e958e53e642e	LifespanCycleState.STARTUP:  'lifespan.startup.complete' event received from application.
    [INFO]	2020-08-22T21:47:22.343Z	19059eac-f60f-13d2-72c7-e958e53e642e	Application startup complete.
    [INFO]	2020-08-22T21:47:22.343Z	19059eac-f60f-13d2-72c7-e958e53e642e	HTTP event received.
    [INFO]	2020-08-22T21:47:23.92Z	19059eac-f60f-13d2-72c7-e958e53e642e	HTTPCycleState.REQUEST:  'http.response.start' event received from application.
    [INFO]	2020-08-22T21:47:23.92Z	19059eac-f60f-13d2-72c7-e958e53e642e	HTTPCycleState.RESPONSE:  'http.response.body' event received from application.
    [ERROR]	2020-08-22T21:47:23.92Z	19059eac-f60f-13d2-72c7-e958e53e642e	Exception in 'http' protocol.
    Traceback (most recent call last):
      File "/var/task/mangum/protocols/http.py", line 79, in run
        await app(self.scope, self.receive, self.send)
      File "/var/task/fastapi/applications.py", line 179, in __call__
        await super().__call__(scope, receive, send)
      File "/var/task/starlette/applications.py", line 111, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/var/task/starlette/middleware/errors.py", line 181, in __call__
        raise exc from None
      File "/var/task/starlette/middleware/errors.py", line 159, in __call__
        await self.app(scope, receive, _send)
      File "/var/task/starlette/exceptions.py", line 82, in __call__
        raise exc from None
      File "/var/task/starlette/exceptions.py", line 71, in __call__
        await self.app(scope, receive, sender)
      File "/var/task/starlette/routing.py", line 566, in __call__
        await route.handle(scope, receive, send)
      File "/var/task/starlette/routing.py", line 227, in handle
        await self.app(scope, receive, send)
      File "/var/task/starlette/routing.py", line 41, in app
        response = await func(request)
      File "/var/task/fastapi/routing.py", line 182, in app
        raw_response = await run_endpoint_function(
      File "/var/task/fastapi/routing.py", line 135, in run_endpoint_function
        return await run_in_threadpool(dependant.call, **values)
      File "/var/task/starlette/concurrency.py", line 34, in run_in_threadpool
        return await loop.run_in_executor(None, func, *args)
      File "/var/lang/lib/python3.8/concurrent/futures/thread.py", line 57, in run
        result = self.fn(*self.args, **self.kwargs)
      File "/var/task/example_app/main.py", line 29, in pong
        import ptvsd; ptvsd.enable_attach(address=('0.0.0.0', 5858), redirect_output=True); ptvsd.wait_for_attach(); ptvsd.break_into_debugger()
      File "/var/task/ptvsd/attach_server.py", line 101, in enable_attach
        ptvsd_enable_attach(address)
      File "/var/task/ptvsd/_remote.py", line 59, in enable_attach
        daemon = install(pydevd,
      File "/var/task/ptvsd/pydevd_hooks.py", line 128, in install
        daemon = Daemon(**kwargs)
      File "/var/task/ptvsd/daemon.py", line 503, in __init__
        super(Daemon, self).__init__(wait_for_user, **kwargs)
      File "/var/task/ptvsd/daemon.py", line 100, in __init__
        self._install_exit_handlers()
      File "/var/task/ptvsd/daemon.py", line 425, in _install_exit_handlers
        self._exithandlers.install()
      File "/var/task/ptvsd/exit_handlers.py", line 62, in install
        self._install_signal_handler()
      File "/var/task/ptvsd/exit_handlers.py", line 103, in _install_signal_handler
        orig[sig] = signal.signal(sig, self._signal_handler)
      File "/var/lang/lib/python3.8/signal.py", line 47, in signal
        handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
    ValueError: signal only works in main thread[INFO]	2020-08-22T21:47:23.107Z	19059eac-f60f-13d2-72c7-e958e53e642e	Waiting for application shutdown.
    [INFO]	2020-08-22T21:47:23.108Z	19059eac-f60f-13d2-72c7-e958e53e642e	LifespanCycleState.SHUTDOWN:  'lifespan.shutdown.complete' event received from application.
    
    opened by dwbelliston 1
  • Can't find valid bootsraps ['uvicorn']

    Can't find valid bootsraps ['uvicorn']

    When the docker corresponding to this repo is built, pushed to ECR, and deployed on Lamda. I am facing the following error: Couldn't find valid bootstrap(s): [uvicorn]", "errorType": "Runtime.InvalidEntrypoint"

    opened by aadeshTrier 0
  • Are Web Sockets supported with this kind of deployment?

    Are Web Sockets supported with this kind of deployment?

    Thanks for the deployment info for FastAPI on Amazon Lambda. Really appreciated.

    Just curious: do you know if Websockets will work?

    https://www.serverless.com/blog/framework-release-v138-websockets

    opened by acidjunk 0
Owner
Ben
geographer turned spatial engineer turned data-something turned software developer
Ben
aws-lambda-scheduler lets you call any existing AWS Lambda Function you have in a future time.

aws-lambda-scheduler aws-lambda-scheduler lets you call any existing AWS Lambda Function you have in the future. This functionality is achieved by dyn

Oğuzhan Yılmaz 57 Dec 17, 2022
Python + AWS Lambda Hands OnPython + AWS Lambda Hands On

Python + AWS Lambda Hands On Python Criada em 1990, por Guido Van Rossum. "Bala de prata" (quase). Muito utilizado em: Automatizações - Selenium, Beau

Marcelo Ortiz de Santana 8 Sep 9, 2022
AWS-serverless-starter - AWS Lambda serverless stack via Serverless framework

Serverless app via AWS Lambda, ApiGateway and Serverless framework Configuration

 Bəxtiyar 3 Feb 2, 2022
Lambda-function - Python codes that allow notification of changes made to some services using the AWS Lambda Function

AWS Lambda Function This repository contains python codes that allow notificatio

Elif Apaydın 3 Feb 11, 2022
SSH-Restricted deploys an SSH compliance rule (AWS Config) with auto-remediation via AWS Lambda if SSH access is public.

SSH-Restricted SSH-Restricted deploys an SSH compliance rule with auto-remediation via AWS Lambda if SSH access is public. SSH-Auto-Restricted checks

Adrian Hornsby 30 Nov 8, 2022
A suite of utilities for AWS Lambda Functions that makes tracing with AWS X-Ray, structured logging and creating custom metrics asynchronously easier

A suite of utilities for AWS Lambda Functions that makes tracing with AWS X-Ray, structured logging and creating custom metrics asynchronously easier

Amazon Web Services - Labs 1.9k Jan 7, 2023
POC de uma AWS lambda que executa a consulta de preços de criptomoedas, e é implantada na AWS usando Github actions.

Cryptocurrency Prices Overview Instalação Repositório Configuração CI/CD Roadmap Testes Overview A ideia deste projeto é aplicar o conteúdo estudado s

Gustavo Santos 3 Aug 31, 2022
The AWS Lambda Serverless Blind XSS App

Ass The AWS Lambda Serverless Blind XSS App 利用VPS配置XSS平台太麻烦了,如果利用AWS的Lambda那不就是一个域名的事情么?剩下的环境配置、HTTPS证书、隐私性、VPS续费都不用管了, 所以根据xless重写了Lambda平台的XSS,利用sla

cocokey 2 Dec 27, 2021
AWS Lambda Fast API starter application

AWS Lambda Fast API Fast API starter application compatible with API Gateway and Lambda Function. How to deploy it? Terraform AWS Lambda API is a reus

OBytes 6 Apr 20, 2022
Automated AWS account hardening with AWS Control Tower and AWS Step Functions

Automate activities in Control Tower provisioned AWS accounts Table of contents Introduction Architecture Prerequisites Tools and services Usage Clean

AWS Samples 20 Dec 7, 2022
Implement backup and recovery with AWS Backup across your AWS Organizations using a CI/CD pipeline (AWS CodePipeline).

Backup and Recovery with AWS Backup This repository provides you with a management and deployment solution for implementing Backup and Recovery with A

AWS Samples 8 Nov 22, 2022
Criando Lambda Functions para Ingerir Dados de APIs com AWS CDK

LIVE001 - AWS Lambda para Ingerir Dados de APIs Fazer o deploy de uma função lambda com infraestrutura como código Lambda vai numa API externa e extra

Andre Sionek 12 Nov 20, 2022
A python library for creating Slack slash commands using AWS Lambda Functions

slashbot Slashbot makes it easy to create slash commands using AWS Lambda functions. These can be handy for creating a secure way to execute automated

Eric Brassell 17 Oct 21, 2022
AWS SQS event redrive Lambda With Python

AWS SQS event redrive Lambda This repository contains one simple AWS Lambda function in Python to redrive AWS SQS events from source queue to destinat

null 1 Oct 19, 2021
AWS SQS event redrive Lambda

This repository contains the Lambda function to redrive sqs events from source to destination queue while controlling maxRetry per event.

null 1 Oct 19, 2021
Building and deploying AWS Lambda Shared Layers

AWS Lambda Shared Layers This repository is hosting the code from the following blog post: AWS Lambda & Shared layers for Python. The goal of this rep

Flaneer 7 Dec 2, 2021
A Python AWS Lambda Webhook listener that generates a permanent URL when an asset is created in Contentstack.

Webhook Listener A Python Lambda Webhook Listener - Generates a permanent URL on created assets. See doc on Generating a Permanent URL: https://www.co

Contentstack Solutions 1 Nov 4, 2021