FastAPI has gained a lot of traction for building APIs quickly and efficiently. If you have a FastAPI project that you want to deploy, Vercel is an excellent option. This tutorial assumes that you already have a FastAPI project and it is git initialized. If not, you should start by creating a FastAPI project and initialize a git repository in the project directory.

Table of Contents

  1. Project Structure
  2. Export Requirements
  3. Add vercel.json File
  4. Push Project to GitHub
  5. Import into Vercel
  6. Continuous Deployment

Project Structure

We are going to be working with a project directory structure which looks something like this. If you have a different structure, make sure to update the vercel.json configuration file to align with your project structure

.
├── app/
│   └── main.py
├── requirements.txt or pyproject.toml
└── vercel.json

Export Requirements

Using pip

To export your Python requirements, you can use pip. In your terminal, navigate to the project directory and run:

pip freeze > requirements.txt

Using Poetry

If you are using poetry, you can export the dependencies to a requirements.txt file with:

poetry export -f requirements.txt --output requirements.txt

Add vercel.json File

Create a new file in the root of your project and name it vercel.json. Add the following JSON content to it:

{
    "devCommand": "uvicorn app:app --host 0.0.0.0 --port 3000",
    "builds": [
        {
            "src": "app/main.py",
            "use": "@vercel/python"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "app/main.py"
        }
    ]
}

Push Project to GitHub

If your project is not already on GitHub, you will need to create a new repository and push your project to it.

Initialize the git repository (if not already initialized):

git init

Add all files and commit them:

git add .
git commit -m "Initial commit"

Push your project to GitHub:

git remote add origin [your-git-repo-url]
git push -u origin master

Import into Vercel

  1. Go to Vercel
  2. Click Import Project
  3. Choose Import Git Repository
  4. Paste your GitHub repository URL and follow the on-screen instructions. Vercel will automatically detect the vercel.json configuration and deploy your FastAPI app.

Continuous Deployment

Vercel integrates seamlessly with your GitHub repository. For subsequent deployments, just push your changes to GitHub.

git add .
git commit -m "Your commit message"
git push origin master

Vercel will automatically deploy the updated code. Visit your Vercel dashboard to check the deployment status and logs.

And that's it! You've successfully deployed a FastAPI application on Vercel. Enjoy your journey in building and scaling your FastAPI apps!

How to Deploy a FastAPI App on Vercel