· Hakan Çelik · Cloud / AWS · 1 dk okuma

How to Deploy a FastAPI Application on AWS Lambda with SAM

If you wrote your serverless application with FastAPI and want to run it on AWS Lambda, you need to make it compatible with Lambda. The library you need for this is mangum.

If you wrote your serverless application with FastAPI and want to run it on AWS Lambda, you need to make it compatible with Lambda. The library you need for this is mangum.

Mangum takes your app and converts it into a handler function — the format that AWS Lambda expects.

Let’s start with an example. Suppose you have an app file called main.py with your FastAPI code and app, just like the following:

from typing import Optional

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

handler = Mangum(app)

By writing it this way, we defined our app and used Mangum to create a variable called handler. This handler is fully compatible with the handler that AWS Lambda expects in its configuration.

Next, we updated our Dockerfile as follows:

FROM python:3.8.10

RUN apt-get update && \
  apt-get install -y \
  g++ \
  make \
  cmake \
  unzip \
  libcurl4-openssl-dev

COPY . /app
WORKDIR /app

RUN pip install --upgrade pip
RUN pip install -r requirements.txt
RUN pip install awslambdaric mangum

RUN chmod +x ./lambda-entrypoint.sh
ENTRYPOINT [ "./lambda-entrypoint.sh" ]
CMD [ "main.handler" ]

The rest is just:

$ sam build
$ sam deploy --guided

That’s all there is to it.

Back to Blog

Related Posts

View All Posts »
Cloud Computing

Cloud Computing

Cloud · 4 dk

Cloud computing is the on-demand delivery of technology resources over the Internet with pay-as-you-go pricing. Instead of buying, owning, and maintaining physical data centers and servers, you can access technology services such as computing power, storage, and databases on an as-needed basis from a cloud provider like Amazon Web Services (AWS).