A Guide to Starting a FastAPI + Poetry + Serverless Project (2024)

Nimish Verma

Posted on

#python #webdev #aws #serverless

(My first DEV.to article)

Hello, in this article I will go over setting up a basic FastAPI app using Poetry, and deploying/packaging it using Serverless. I will also go over Serverless Lift, and use it to generate a DynamoDB instance.

If you are already aware of the technologies mentioned above, please skip to the next section.

Section 1 - Introduction to the Technologies.

FastAPI

FastAPI is a Python-based web framework based on ASGI (Starlette) that is used to make APIs, mostly. As the name suggests, it is much faster than Django and Flask, and comes with a few features (as compared to the star-studded Django) such as pydantic typing, and OpenAPI documentation. I have written an article on FastAPI over here.

Poetry

Poetry is a package manager for Python. For people with background in Javascript, can think of it as a npm manager. Just like package.json (poetry.toml) and package-lock.json (poetry.lock), Poetry maintains dependency tree, virtual environments, and also comes with a CLI.

Using Poetry is not mandatory, I personally am new to it too. Poetry allows us to manage config dependencies and resolve dependency issues which normally occur in old/unmaintained third party libraries that results in conflicted dependencies. Not only that, it allows a better reproduction of the environment and publishing to Pypi.

To install Poetry CLI run curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - for osx, linux; and for windows run (Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python - in Powershell. More instructions here

Serverless

Serverless is gaining a lot of popularity as we are transitioning to a microservices architecture. Serverless comes with a CLI and a dashboard that helps you monitor your serverless functions on a variety of different cloud providers. It provides a higher level layer to monitor and deploy these functions easily.

I have been using Serverless for a bunch of different side projects and it comes with various plugins to make deployment easier for cloud infrastructures.

To install Serverless CLI, download using curl -o- -L https://slss.io/install | bash or npm install -g serverless

Section 2 - Starting a FastAPI project with Poetry

After having installed Poetry, let us initialize a poetry project.

poetry new my-project # change project name to whatever you want

This creates a python package with a README, tests directory, and a couple of poetry files. Next we install fastapi using

poetry add fastapi uvicorn[standard]

These two are required in order to start a FastAPI project and run the ASGI Starlette server.

In my-project/my-project we create our app.py, a pretty basic one for the sake of this project. We write two endpoints for now as follows-

from fastapi import FastAPIimport osstage = os.environ.get('STAGE', 'dev')app = FastAPI()@app.get("/")def index(): return {"Hello": "World"}@app.get("/users/{user_id}")def read_item(user_id: int): return {"user_id": user_id}

To run this project, normally we would run using

uvicorn my-project.app:app

Step 3 - Serverless Packaging and Deployment

Now we make a serverless.yml in the root folder my-project

service: My-Projectpackage: individually: trueprovider: name: aws profile: ${opt:aws-profile, "default"} region: "us-west-2" stage: ${opt:stage, "dev"} runtime: python3.8plugins: - serverless-offline - serverless-python-requirementscustom: pythonRequirements: dockerizePip: true usePoetry: truefunctions: app: handler: my-project.app.handler #I will explain why we have handler here environment: STAGE: ${self:provider.stage} events: - http: method: get path: / - http: method: any path: /{proxy+}

This is pretty easy to understand, we use the standard python packaging plugin for serverless called serverless-python-requirements. It packages the python project that contains a requirements.txt or a poetry/pipenv package. We point our handler to the app.py.

Right now the app file does not export any handler, so you might be wondering why did I not use app.app instead. This is because we have to wrap our ASGI app to adapt AWS Lambda and API Gateway. For that we use Mangum.

First we install mangum using

poetry add mangum

Next we wrap our app into mangum using the following addition to app.py

from mangum import Mangumhandler = Mangum(app)

This makes our ASGI app (FastAPI) support API Gateway for HTTP, REST, and WebSockets.

Before proceeding to next step we just have to initialize our npm project and install serverless-python-requirements to it, since serverless is a node package.

In the project root run

npm init --yesnpm install serverless-python-requiremnts

Step 4 - Using Serverless Lift [🎁BONUS🎁]

Serverless Lift provides another abstraction layer over the AWS SDK to initialize and deploy services like storage, webhooks, static pages, databases, queues and more! We are gonna install it using

serverless plugin install -n serverless-lift

and add it to our serverless.yml which should look like

plugins: - serverless-offline - serverless-python-requirements - serverless-lift

Next, we are gonna construct a DynamoDB table (single table) and use it to access user information in our database.

With the following code in serverless.yml we will have the following handled automatically:
⭐ Deploy, if not already exists, a DynamoDB table with generic PK and SK, and up to 20 configurable secondary composite indices called GSIs with generic PKs and SKs for each of them.
⭐ Stream setup with OLD_IMAGES and NEW_IMAGES
⭐ Other small setup configs such as cost set to pay per req and TTL enabled.
⭐ Automatically assigned necessary permissions to your lambda functions in this yaml file.
⭐ Variable name injection for table name and stream name

constructs: myTable: type: database/dynamodb-single-tablefunctions: app: handler: my-project.app.handler environment: STAGE: ${self:provider.stage} TABLE_NAME: ${construct:myTable.tableName} events: - http: method: get path: / - http: method: any path: /{proxy+}

Now in our app.py we can access this table name and don't have to worry about assigning the lambda an IAM role.

For the users endpoint we can do the following (make sure you populate your DB first obviously, but this is just for the sake of an example):

@app.get("/users/user_id")def read_item(user_id: int): table_name = os.environ.get('TABLE_NAME', '') table = boto3.resource("dynamodb", region_name='us-west-2').Table(table_name) response = table.get_item( Key={ 'PK': user_id } ) return {"user_obj": response['Item']}

To make this run just install boto3

poetry add boto3

Et voila!

Step 5 - Testing and Deploying

To test this locally we run

serverless offline --stage dev --noPrependStageInUrl

If you dont include the --noPrependStageInUrl flag, it will run your server at localhost:3000/dev/{proxy}+. If you to run it like that, make sure you include root_path='dev' parameter in app=FastAPI() to see the docs

We see that it runs locally, and also shows us the docs. To deploy this we use

serverless deploy --stage dev #or prod

And serverless will deploy it in our AWS profile, as long as you have the initial serverless config setup.

Known issue of serverless-python-requirements is that it will throw a Poetry not found error when you try to deploy or package the sls project. To fix that please go node_modules/serverless-python-requirements/lib/poetry.js and replace the res at line 17 with

 const res = spawnSync( 'poetry', [ 'export', '--without-hashes', '-f', 'requirements.txt', '-o', 'requirements.txt', '--with-credentials', ], { cwd: this.servicePath, shell: true // <- we added this  } );

This will prevent that issue. Kudos to this issue creator

Hi,

I'm on Windows10. Serverless environment:

Your Environment Information ---------------------------Operating System: win32Node Version: 14.15.4Framework Version: 2.42.0Plugin Version: 5.1.2SDK Version: 4.2.2Components Version: 3.10.0

Version of plugin:

5.1.1

I'm using poetry and according to the documentation, this should work fine. From the doc:

If you include a pyproject.toml and have poetry installed instead of a requirements.txt this will use poetry export --without-hashes -f requirements.txt -o requirements.txt --with-credentials to generate them.

But I ran into this error when I tried to deploy:

PS > serverless deployServerless: Generating requirements.txt from pyproject.toml...

Error ---------------------------------------------------

Error: poetry not found! Install it according to the poetry docs.at ServerlessPythonRequirements.pyprojectTomlToRequirements (C:<path replaced>\node_modules\serverless-python-requirements\lib\poetry.js:34:13)

After some research I found this comment: https://stackoverflow.com/a/54515183/5759828 suggesting to use {shell:true}. As part of my testing I found that the output of spawnSync (line 17 in poetry.js) is:

error: Error: spawnSync poetry ENOENT

I then added shell:true to poetry.js like this:

const res = spawnSync( 'poetry', [ 'export', '--without-hashes', '-f', 'requirements.txt', '-o', 'requirements.txt', '--with-credentials', ], { cwd: this.servicePath, shell: true <--- added this } );

and now it works fine.

🎉🎉🎉🎉
If you read it till here, thank you for reading the article. Make sure you share and like this article. If you think there is a fault or if I missed something, please reach out.
The code for this is hosted on Github in case anyone is interested.

A Guide to Starting a FastAPI + Poetry + Serverless Project (4) NimishVerma / ServerlessFastapiPoetry

Could not have thought of a better name, lol

References

  1. https://pythonrepo.com/repo/tiangolo-poetry-version-plugin-python-package-dependency-management
  2. https://towardsdatascience.com/fastapi-aws-robust-api-part-1-f67ae47390f9
  3. https://levelup.gitconnected.com/using-poetry-with-serverless-framework-to-deploy-python-lambda-functions-8dd424727a03
A Guide to Starting a FastAPI + Poetry + Serverless Project (2024)

FAQs

Is FastAPI production ready? ›

While an open-source framework, FastAPI is fully production-ready, with excellent documentation, support, and an easy-to-use interface.

How do you deploy FastAPI to Lambda? ›

Tutorial
  1. Create a directory for your application. To start, create a new directory and cd into it. ...
  2. Create a simple FastAPI application. ...
  3. Specify runtime dependencies. ...
  4. Create a SAM template. ...
  5. Test your API locally with SAM CLI. ...
  6. Deploy your API to AWS. ...
  7. Call your newly deployed API.
23 Dec 2021

How do I deploy FastAPI app? ›

Deploy FastAPI on Deta
  1. A basic FastAPI app. Create a directory for your app, for example, ./fastapideta/ and enter into it. ...
  2. Create a free Deta account. Now create a free account on Deta, you just need an email and password. ...
  3. Install the CLI. ...
  4. Login with the CLI. ...
  5. Deploy with Deta. ...
  6. Check it. ...
  7. Enable public access. ...
  8. HTTPS.

Does Netflix use FastAPI? ›

Its performance can be compared with NodeJS and Go and it is rated as one of the fastest Python frameworks available. Netflix, Uber, Microsoft amongst many other corporations are using the FastAPI library. FastAPI can help us build APIs with Python 3.6+.

Is FastAPI worth learning? ›

Excellent performance

FastAPI is actually known as one of the fastest Python web frameworks. In fact, only Starlette and Uvicorn, on which FastAPI is built, are faster. This superior performance is enabled precisely by ASGI, thanks to which FastAPI supports concurrency and asynchronous code.

Is FastAPI better than Django? ›

In conclusion, Django is perfect if you want to build robust full-stack web applications because it has several functionalities and works very well in production. On the other hand FastAPI is perfect if you're looking for high performance or scalable applications.

Is FastAPI better than Flask? ›

FastAPI surpasses Flask in terms of performance, and it is one of the fastest Python web frameworks. Only Starlette and Uvicorn are faster. Because of ASGI, FastAPI supports concurrency and asynchronous code by declaring the endpoints. For concurrent programming, Python 3.4 introduced Async I/O.

What companies use FastAPI? ›

117 companies reportedly use FastAPI in their tech stacks, including Primer, Back-end, and Payhere.
  • Primer.
  • Back-end.
  • Payhere.
  • Postclick.
  • yogiyo.
  • Tech-Stack.
  • Sendcloud.
  • TravelPerk.

How do I run FastAPI on AWS? ›

This blog will see how we can deploy a FastAPI application on AWS EC2 instance using Docker and NGINX.
  1. Step 1: Create an API using FastAPI. ...
  2. Step 2: Spin up your EC2 Instance. ...
  3. Step 3: Install Docker and NGINX on your Server. ...
  4. Step 4: Get all Application Files. ...
  5. Step 5: Setup NGINX. ...
  6. Step 6: Start the Docker Container.
4 Feb 2022

Is FastAPI a Microservice? ›

FastAPI has recently become one of the most popular web frameworks used to develop microservices in Python. FastAPI is much faster than Flask (a commonly used web framework in Python) because it is built over an Asynchronous Server Gateway Interface (ASGI) instead of a Web Server Gateway Interface (WSGI).

What is the difference between lambda and EC2? ›

Compared to AWS Lambda, EC2 runs a full copy of the operating system and all the necessary hardware to run the OS. Managing and provisioning the EC2 environment is therefore required. On the other hand, Lambda only needs a few system resources and dependencies to run a specific function. AWS handles everything else.

Is FastAPI faster than node? ›

Express (NodeJS) is ~1.5x faster than FastAPI (Python) and, these frameworks are ~7.5 and ~11.35 times slower than Fiber (as per multi-core async performance).

Is FastAPI a REST API? ›

They use HTTP requests to manipulate data and communicate with web services. REST APIs are stateless, cacheable, and consistent. They're great for building general-purpose and scalable web applications. The three major Python frameworks are Django, Flask, and FastAPI.

How can I learn API fast? ›

Using FastAPI to Build Python Web APIs
  1. Create a First API.
  2. Run the First API App With Uvicorn.
  3. Check the Response.
  4. Check the Interactive API Documentation.
  5. Check the Alternative Interactive API Documentation.
  6. The First API, Step by Step.

Does uber use FastAPI? ›

FastAPI was the third most loved web framework in Stack Overflow 2021 Developer Survey. T. Danka stressed its value for data science applications. It is used by large companies like Uber and Netflix to develop some of their applications.

Is FastAPI good for large projects? ›

FastAPI performs significantly better in terms of efficiency. This happens as a result of asynchronous request processing. This makes FastAPI superior to Flask for larger-scale machine learning projects, especially enterprise ones, as it can handle requests much more efficiently.

Who owns FastAPI? ›

Ramirez is the creator of FastAPI, the fastest growing and one of the most popular Python web frameworks in the world. He has spent the last nine years building products and custom solutions for data and machine learning systems, and leading teams of developers all over the world, from Latin America to the Middle East.

Is FastAPI faster than go? ›

FastAPI's website claims that FastAPI is as fast as Golang. Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.

Why FastAPI is so fast? ›

It is a modern framework that allows us to build API seamlessly without much effort and time. As the name itself is fast, it is much faster than the flask because it's built over ASGI (Asynchronous Server Gateway Interface) instead of WSGI (Web Server Gateway Interface) s the flask is built on.

How much faster is FastAPI? ›

The same 50 websites are downloaded in 1 second, which is 5 times faster than the synchronous code! In benchmarks with NodeJS, FastAPI is faster in almost all cases.

Do companies use FastAPI? ›

FastAPI was the third most loved web framework in Stack Overflow 2021 Developer Survey. T. Danka stressed its value for data science applications. It is used by large companies like Uber and Netflix to develop some of their applications.

Is FastAPI better than flask? ›

FastAPI surpasses Flask in terms of performance, and it is one of the fastest Python web frameworks. Only Starlette and Uvicorn are faster. Because of ASGI, FastAPI supports concurrency and asynchronous code by declaring the endpoints. For concurrent programming, Python 3.4 introduced Async I/O.

Is FastAPI better than Django? ›

In conclusion, Django is perfect if you want to build robust full-stack web applications because it has several functionalities and works very well in production. On the other hand FastAPI is perfect if you're looking for high performance or scalable applications.

Do I need Gunicorn with Uvicorn? ›

Running with Gunicorn

For production deployments we recommend using gunicorn with the uvicorn worker class. For a PyPy compatible configuration use uvicorn.

How many requests can FastAPI handle? ›

FastAPI (Async) - Python

FastAPI in asynchronous mode clocks in at ~228 requests per second.

Is FastAPI good for large projects? ›

FastAPI performs significantly better in terms of efficiency. This happens as a result of asynchronous request processing. This makes FastAPI superior to Flask for larger-scale machine learning projects, especially enterprise ones, as it can handle requests much more efficiently.

Will FastAPI replace Django? ›

Performance: FastAPI, being a minimalistic framework, is lightweight as compared to Django and hence offers very high performance, whereas Django is not as fast as compared to FastAPI, which is a micro framework. Learning curve: FastAPI is very easy to learn and is helpful for those who are new to web development.

What companies use FastAPI? ›

117 companies reportedly use FastAPI in their tech stacks, including Primer, Back-end, and Payhere.
  • Primer.
  • Back-end.
  • Payhere.
  • Postclick.
  • yogiyo.
  • Tech-Stack.
  • Sendcloud.
  • TravelPerk.

Why is FastAPI so popular? ›

FastAPI is easy to learn, is lightweight, and can be used to build small-scale websites and applications. It comes with an object-relational mapping (ORM) layer that handles data objects in the application so that you can access them quickly through coding.

Is FastAPI a Microservice? ›

FastAPI has recently become one of the most popular web frameworks used to develop microservices in Python. FastAPI is much faster than Flask (a commonly used web framework in Python) because it is built over an Asynchronous Server Gateway Interface (ASGI) instead of a Web Server Gateway Interface (WSGI).

Is FastAPI enough for backend? ›

Thus, the FastAPI framework is a great choice for new developers to experiment and explore backend development in, if they are proficient with the Python programming language.

What makes FastAPI fast? ›

Speeding up Python with concurrency

Currently at version 0.70. 0, FastAPI is rapidly climbing up the popularity ranks. One of the reasons is that it does what it says: it's fast. Not because it's lightweight, but because it has out-of-the-box support for concurrency (asynchronous functions, requires Python 3.6+).

Is Django a FastAPI? ›

Differences between Django and FastAPI. As we know, Django is a mega framework for building web applications, whereas FastAPI is a minimalistic framework based on Starlette and Pydantic for building fast web applications using async IO.

Is Uvicorn better than Gunicorn? ›

Uvicorn and Gunicorn are both open source tools. It seems that Gunicorn with 7.06K GitHub stars and 1.33K forks on GitHub has more adoption than Uvicorn with 2.94K GitHub stars and 214 GitHub forks.

Can I run Uvicorn in production? ›

Gunicorn is probably the simplest way to run and manage Uvicorn in a production setting. Uvicorn includes a gunicorn worker class that means you can get set up with very little configuration. The UvicornWorker implementation uses the uvloop and httptools implementations.

Which is better Gunicorn or uWSGI? ›

Gunicorn and uWSGI are primarily classified as "Web Servers" and "Web Server Interface" tools respectively. Gunicorn and uWSGI are both open source tools. Gunicorn with 5.96K GitHub stars and 1.12K forks on GitHub appears to be more popular than uWSGI with 2.5K GitHub stars and 541 GitHub forks.

Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 5750

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.