Deploying Your FastAPI App on Heroku: A Complete Walkthrough
Prerequisites
To successfully deploy your FastAPI app on Heroku, ensure you have the following prerequisites:
- Python Installed: FastAPI requires Python 3.6 or later.
- Heroku CLI: Download and install the Heroku Command Line Interface (CLI) from the Heroku website.
- Git Installed: Version control is important, so have Git installed on your machine.
- A Heroku Account: Sign up for a free account at Heroku if you don’t have one.
Step 1: Setting Up Your FastAPI Project
Begin by setting up your FastAPI app. If you haven’t created one yet, you can quickly scaffold a new FastAPI application using the following steps:
-
Create a new directory for your project:
mkdir fastapi-heroku-project cd fastapi-heroku-project -
Create a virtual environment:
python -m venv venv source venv/bin/activate # On Windows use `venvScriptsactivate` -
Install FastAPI and an ASGI server like
uvicorn:pip install fastapi uvicorn -
Create a
main.pyfile in your project directory:from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"}
Step 2: Prepare for Deployment
Now that your FastAPI application is ready, the next step involves preparing it for deployment to Heroku.
-
Create a requirements.txt file: Heroku needs to know which packages you are using. Generate this file with:
pip freeze > requirements.txt -
Create a Procfile: This file tells Heroku how to run your application. Create a file named
Procfilein the root directory:web: uvicorn main:app --host=0.0.0.0 --port=${PORT} -
Add a runtime.txt file: Specify the Python version with this file. The content should look like:
python-3.9.12 # Adjust this version based on your requirements -
Ensure your application is ready for production: You should have CORS, logging, and other production settings configured. For example, to enable CORS, you can modify your FastAPI app as follows:
from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Update allowed origins as needed allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
Step 3: Initialize Git Repository
Heroku uses Git for deployment, so you need to initialize a Git repository:
git init
git add .
git commit -m "Initial commit"
Step 4: Log into Heroku
Open your terminal and run the following command to log into your Heroku account:
heroku login
This command will trigger a web page for you to authenticate your Heroku credentials.
Step 5: Create a Heroku App
Create a new app on Heroku with the desired name (replace your-app-name with a unique name):
heroku create your-app-name
Step 6: Deploy to Heroku
With your FastAPI app set up, you’re ready to deploy it. First, add the Heroku remote to your Git:
heroku git:remote -a your-app-name
Now, push your changes to Heroku:
git push heroku master
Step 7: Access Your App
Once the deployment is successful, you can access your FastAPI app through the URL provided by Heroku, typically https://your-app-name.herokuapp.com.
Step 8: View Logs
To troubleshoot or monitor your application, you can view the logs with:
heroku logs --tail
This command will display real-time logs, making it easier to debug issues.
Step 9: Set Environment Variables
If your app relies on environment variables (e.g., API keys or database URLs), you can set them directly in Heroku:
heroku config:set VARIABLE_NAME=value
Step 10: Scaling Your App
By default, your app will have one web dyno. If you need to scale your application, you can do so with:
heroku ps:scale web=1
Replace 1 with the number of dynos you want to run.
Step 11: Debugging Common Issues
During deployment or usage, you may encounter issues. Common problems include:
- Dependency Issues: Ensure all required packages are listed in
requirements.txt. - Configuration Errors: Check for misconfigurations in
Procfileor environment variables. - CORS Errors: Troubleshoot CORS-related issues by verifying allowed origins.
Step 12: Continuous Deployment
For continuous integration and deployment (CI/CD), consider integrating Heroku with GitHub. This allows automatic deployments upon new pushes to specific branches.
Step 13: Additional Resources
For further improvements to your FastAPI app, you can explore:
- Heroku’s Add-ons: Enhance your application with databases, monitoring, and more.
- FastAPI Documentation: For best practices and advanced features, consult the FastAPI documentation.
- Heroku Documentation: Explore the broader capabilities of Heroku at their Dev Center.
By following these comprehensive steps, you can deploy your FastAPI application on Heroku efficiently, ensuring your application can be accessed from anywhere globally. Optimize your APIs, leverage Heroku’s powerful infrastructure, and enjoy the scalability and flexibility this platform offers.