0
0
FastapiHow-ToBeginner · 4 min read

How to Deploy FastAPI to Heroku: Step-by-Step Guide

To deploy FastAPI to Heroku, create a Procfile specifying the command to run uvicorn, add a requirements.txt with dependencies, and push your code to a Heroku Git repository. Heroku will build and run your FastAPI app automatically using these files.
📐

Syntax

Deploying FastAPI to Heroku requires these key files:

  • Procfile: Tells Heroku how to start your app using uvicorn.
  • requirements.txt: Lists Python packages your app needs.
  • runtime.txt: (Optional) Specifies Python version.
  • app.py: Your FastAPI application code.

The Procfile usually contains: web: uvicorn app:app --host=0.0.0.0 --port=${PORT:-5000} where app:app means the file app.py and the FastAPI instance named app.

bash
web: uvicorn app:app --host=0.0.0.0 --port=${PORT:-5000}
💻

Example

This example shows a minimal FastAPI app ready for Heroku deployment. It includes app.py, requirements.txt, and Procfile.

python
# app.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello from FastAPI on Heroku!"}

# requirements.txt
fastapi
uvicorn[standard]

# Procfile
web: uvicorn app:app --host=0.0.0.0 --port=${PORT:-5000}
Output
When deployed, visiting the root URL returns JSON: {"message": "Hello from FastAPI on Heroku!"}
⚠️

Common Pitfalls

Common mistakes when deploying FastAPI to Heroku include:

  • Not specifying --host=0.0.0.0 in the Procfile, causing the app to listen only on localhost.
  • Forgetting to use the ${PORT} environment variable Heroku assigns, leading to port binding errors.
  • Missing dependencies in requirements.txt, so Heroku can't install needed packages.
  • Not committing all files to Git before pushing to Heroku.

Example of a wrong Procfile and the fix:

bash
# Wrong Procfile
web: uvicorn app:app

# Correct Procfile
web: uvicorn app:app --host=0.0.0.0 --port=${PORT:-5000}
📊

Quick Reference

FilePurposeExample Content
ProcfileStart command for Herokuweb: uvicorn app:app --host=0.0.0.0 --port=${PORT:-5000}
requirements.txtPython dependenciesfastapi uvicorn[standard]
app.pyFastAPI app codefrom fastapi import FastAPI app = FastAPI() @app.get('/') async def root(): return {"message": "Hello"}
runtime.txtPython version (optional)python-3.11.4

Key Takeaways

Always use a Procfile with uvicorn specifying host 0.0.0.0 and port from Heroku's PORT variable.
Include all dependencies in requirements.txt for Heroku to install them correctly.
Push all your files to Heroku Git repository to trigger deployment.
Test your app locally with uvicorn before deploying to catch errors early.
Optionally specify Python version in runtime.txt to control environment.