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.
- requirements.txt: This file will have all your dependencies. Run:
pip freeze > requirements.txt
in your dev environment to get this file. - vercel.json: This file contains information for vercel to set up your runtime when deploying.
- main.py: This python file can be named differently but it should contain the FastAPI app.
# 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.dest
to 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 👋.
Top comments (4)
This helped! Thank you!
what about routes
I'm getting this error
Error: A Serverless Function has exceeded the unzipped maximum size of 250 MB.
You may want to try using .gitignore inside the proejct folder to only include the bare minimum required files