Introduction
I usually only deploy Next.js apps to Vercel and haven't really looked into the other runtimes that they offer for running serverless functions. In this article we will deploy a FastAPI app to Vercel, using the Python serverless runtime.
Set up FastAPI app
We set up the FastAPI app as follows:
mkdir fastapi-vercel
cd fastapi-vercel
# Create virtual environment
python3 -m venv venv
source venv/bin/activate
# Install FastAPI
pip install fastapi uvicorn
We now create our api.py
file in the server directory:
# server/api.py
from fastapi import FastAPI
from .routes import router as NoteRouter
app = FastAPI()
@app.get("/", tags=["Deploy FastAPI to Vercel"])
async def root() -> dict:
return {"message": "Hello world"}
Now we create main.py as our app root:
# main.py
import uvicorn
if __name__ == "__main__":
uvicorn.run("server.api:app", host="0.0.0.0", port=8000, reload=True)
Now to run the dev server just run:
python3 main.py
Navigate to http://localhost:8000/docs to see your beautiful OpenAPI docs page.
Deploying to Vercel
Firstly ensure you have the Vercel CLI installed:
npm i -g vercel
We first need a vercel.json
file in the root directory to handle to config:
{
"builds": [{ "src": "/server/api.py", "use": "@vercel/python" }],
"routes": [{ "src": "/(.*)", "dest": "server/api.py" }]
}
We can now deploy to Vercel:
vercel .
The first time you will need to authenticate with Vercel, and if you wish you can link a Github repository to have builds run on each push.