Skip to content

Deploying FastAPI app on Vercel Serverless

Updated: at 08:03 PM

Deploying FastAPI app on Vercel Serverless | abdadeel

Table of contents

Open Table of contents

Introduction

There are good chances that I don’t explain what is vercel if you’re a javascript developer but for python folks out there, vercel is a cloud computing platform focused on serverless hosting solutions for web applications. It’s especially popular among developers using frontend frameworks like Next.js, Nuxt.js, and SvelteKit.

This article aims to act as a quick guide if you want to deploy a FastAPI application serverless leveraging python runtime. Moreover, vercel is free so 🤞.

Primarily, you need these three files set up in your application.

# main.py
from fastapi import FastAPI

app = FastAPI() # This is what will be refrenced in config

Assuming the given file structure:

root_dir
|
|__ main.py
|__ requirements.txt
|__ vercel.json

add this in vercel.json

{
  "builds": [
    {
      "src": "main.py",
      "use": "@vercel/python"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "main.py"
    }
  ]
}

If your application structure is different, change build.src and routes.destto point to the python file containing the root application app.
After your app is ready, push the source code to GitHub for seamless automatic future deployments with vercel.

Visit vercel and create an account if you don’t already have one.
Create a new application and connect it to the appropriate GitHub repo.
Additionally in the environment variable section, you might need to configure the port. Copy and paste PORT=8000 in the key field. If you have other environment variables that your application expects like database config, feel free to add those here too.

Hit deploy and in moments, your API is up and running.

Demo Application

https://vercel-fastapi-deployment.vercel.app

Source Code

https://github.com/mabdullahadeel/vercel-fastapi-deployment

Until next time 👋.