admin管理员组

文章数量:1130221

I deployed a FastAPI endpoint using AWS Lambda with the Serverless Framework. I tested the Lambda function locally, and it runs perfectly, but when I deploy it and hit the URL, I receive an "Internal Server Error" (500) in the browser.

After checking the logs, I found the following error:

    [ERROR] Runtime.ImportModuleError: Unable to import module 'handler': No module named 'fastapi'
Traceback (most recent call last):
INIT_REPORT Init Duration: 99.52 ms     Phase: init     Status: error   Error Type: Runtime.ImportModuleError

//handler.py

    from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, this is Daksh from FastAPI on AWS Lambda!"}

handler = Mangum(app)

//serverless.yml

    org: daksh
service: fastapi-lambda

provider:
  name: aws
  runtime: python3.10
  region: ap-northeast-1
  deploymentBucket:
    name: fastapi-lambda-deployments-347775769886

functions:
  app:
    handler: handler.handler
    events:
      - http:
          path: /{proxy+}  
          method: any
    memorySize: 128 
    timeout: 10  
    environment:
      PYTHONPATH: "/var/runtime:/var/task"

package:
  exclude:
    - node_modules/**
    - env/**
    - .serverless/**

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: non-linux
    layer: 
      path: requirements.txt
      name: fastapi-serverless-lambda
      compatibility: python3.10

//requirements.txt

fastapi==0.115.6
mangum==0.19.0
# other packages

What I Have Tried:

  • I am able to run the Lambda function locally using the Serverless Framework without issues. -The function is successfully deployed, but I am seeing the Runtime.ImportModuleError in the logs indicating that fastapi is not found.
  • I am using the serverless-python-requirements plugin to handle dependencies. What could be the cause of this error, and how can I resolve it to make FastAPI work with AWS Lambda?

本文标签: