Deploying FastAPI to Heroku
In the next installment of my quick tutorials for learning FastAPI, let’s examine the basics of deploying a FastAPI application to Heroku. Full disclosure, I have no affiliation with Heroku. I just find their Python app deployment extremely simple.
Our goal is to deploy the bare bones Slack clone discussed previously. As you may recall, this API enables you to store and view messages by channel. It’s also intentionally simple, uses an in-memory data structure, and does not connect to a real database. This makes for much simpler code, so we can focus on the FastAPI parts. It also makes for a much simpler deployment to Heroku, as no database backend is needed.
To deploy to Heroku, you first need to sign up for a free Heroku account. Once you are registered, the next step is to install the Heroku Command Line Interface (CLI). One installed, try logging into Heroku:
heroku login
This will automatically open your web browser for you to authenticate.
Once authenticated, you are ready to go.
I have created all the files needed for deployment, and posted everything up on GitHub. This repository has everything you need, including:
- slack.py: Our original FastAPI code.
- requirements.txt: A list of Python dependencies, including FastAPI, uvicorn and gunicorn.
- runtime.txt: Tells Heroku that we want to run on Python-3.8.5; and
- Procfile: Provides Heroku with a start-up command.
In our case, our Procfile is:
web: gunicorn -w 3 -k uvicorn.workers.UvicornWorker slack:app
This tells Heroku to run the gunicorn HTTP server with three workers and attach it to our slack application.
To deploy our app, we first type:
heroku create
This will create a namespace for our application, such as frozen-sands-58319.
Then, deploy:
git push heroku main
This deploys your code to Heroku, installs all the Python dependencies, and then starts gunicorn. It’s magic!
If all goes well, you can then open you app:
heroku open
This will open your web browser to the root level of your Heroku application. To view your API in action, just append /docs to the URL, and you should see the interactive FastAPI documentation for your endpoints.
If the above doesn’t work, try:
heroku logs --tail
For more complete details on deploying Python apps to Heroku, see Getting Started on Heroku with Python.