Skip to main content

Deploying on Heroku

FastAPI is an excellent web framework for building APIs with Python based on standard Python type hints. Now that you've built your FastAPI application, it's time to deploy it, and Heroku is one of the most beginner-friendly platforms to do so.

Setting Up Your Application

Before we begin, make sure your FastAPI application is structured like this:

.
├── app
│ ├── main.py
├── Procfile
├── requirements.txt
└── runtime.txt

In this structure:

  • app/main.py is where your FastAPI application lives.
  • Procfile will be used by Heroku to start your application.
  • requirements.txt lists the Python libraries your application depends on.
  • runtime.txt specifies the Python version for Heroku to use.

Setting Up Procfile

A Procfile is a mechanism for declaring what commands are run by your application's dynos on the Heroku platform. For our FastAPI application, it should look like this:

web: uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}

This command tells Heroku to run your FastAPI application using uvicorn, a lightning-fast ASGI server.

Setting Up requirements.txt

In requirements.txt, you'll need to include:

fastapi
uvicorn
gunicorn
python-multipart

This list can grow depending on the libraries your application uses.

Setting Up runtime.txt

In runtime.txt, specify your Python version like this:

python-3.9

Deploying to Heroku

Now that your application is set up, you can deploy to Heroku by following these steps:

  1. If you haven't already, sign up for a free Heroku account.

  2. Install the Heroku CLI by following the instructions on the Heroku Dev Center.

  3. Once installed, you can use the heroku login command to log in to the Heroku CLI.

  4. Navigate to the root directory of your project and initialize a Git repository if you haven't already:

    git init
  5. Create a new Heroku app:

    heroku create your-app-name
  6. Add all your files to the Git repository and make a commit:

    git add .
    git commit -m "Initial commit"
  7. Push your application to Heroku:

    git push heroku master
  8. Now, Heroku will receive the push, build your application, and deploy it.

  9. Once the build completes, you can open your application in the web browser:

    heroku open

Congratulations, you've successfully deployed your FastAPI application to Heroku! Now your application is accessible to the world. Remember to keep your application up-to-date with the latest security updates and improvements. Happy coding!