Deploy FastAPI on Vercel: How to Host Your Python APIs for Free
A Step-by-Step Guide to Deploying FastAPI on Vercel with GitHub Integration
I’ve always enjoyed hosting web projects for my portfolio, but when Heroku ended its free-tier service in 2022, I needed a new solution. This year, I discovered Vercel—a fantastic alternative that offers seamless, free hosting for Python APIs.
In this tutorial, I will guide you through setting up your first Python API using GitHub and Vercel.
Why host on Vercel?
Vercel is a cloud platform that offers a fast and reliable way to build and deploy web applications. It's designed to streamline the development and deployment process for modern web projects, particularly those built with frameworks like React, Vue, Next.js, and recently, FastHTML (a Python HTML support library).
How is Vercel different from AWS, GCP, and Azure?
While cloud platforms such as AWS and GCP offer general-purpose cloud platforms offering a wide range of services, Vercel is specifically tailored for web development. Here are some key differences:
Streamlined, developer-friendly platform for web applications.
Simple setup, ideal for non-experts; AWS and GCP are more complex.
Optimized with a global CDN and edge network for faster response times.
Free plan available, making it accessible for small projects and startups.
Building a Python API with FastAPI
APIs are the backbone of modern software development. They enable different systems and applications to communicate seamlessly with each other.
When building AI-powered APIs, Python stands out for its versatility and growing popularity, especially in fields like AI, data science, and web development. FastAPI has emerged as a robust and high-performance option among the frameworks available for API development in Python.
Why FastAPI for Python APIs?
FastAPI is a modern Python web framework built specifically for building APIs. It has gained rapid popularity for a few key reasons:
Speed (performance comparable to frameworks like Node.js and Go)
Asynchronous Support
Automatic Documentation
Data Validation
Easy Integration with AI Models
API 101: A Simple “Hello World” Example
Now, let’s dive into a simple example to demonstrate how easy it is to build your first API.
Prerequisites:
Make sure you have Python 3 installed and install FastAPI and Uvicorn (ASGI server) using pip:
pip install fastapi uvicorn
Step 1: Creating the FastAPI Application
Create a Python file, main.py
, and add the following code to define a basic API:
# main.py
from fastapi import FastAPI
# Create an instance of FastAPI
app = FastAPI()
# Define a root route ("/")
@app.get("/")
async def root():
return {"message": "Hello, World!"}
Here’s what’s happening:
We import FastAPI and create an instance of the app.
We define a route (
/
) using the decorator@app.get("/")
, which maps HTTP GET requests to this function.The function
root()
returns a simple JSON response with a “Hello, World!” message.
Step 2: Running the API
To run the API, use Uvicorn:
uvicorn main:app --reload
main:app
refers to theapp
object in themain.py
file.The
--reload
flag allows for automatic reloading of the server when you make changes to the code (great for development).
Once the server is running, navigate to http://127.0.0.1:8000
in your browser, and you should see the following output:
{ "message": "Hello, World!" }
Deploying FastAPI App on Vercel
Using Vercel’s GitHub integration, we can quickly deploy and manage the FastAPI project for free.
Prerequisites:
A Vercel account (sign up at vercel.com)
A GitHub account
A FastAPI project (like the “Hello World” API discussed in the previous section)
Prepare the FastAPI Project for Deployment
Before deploying to Vercel, make sure the project is properly structured and configured.
Create a Project Directory: If you haven’t already, create a new directory for the FastAPI project.
mkdir fastapi-vercel
cd fastapi-vercel
List Dependencies: To ensure your library dependencies are installed on Vercel, create a
requirements.txt
file and list all your dependencies.
fastapi==0.100.1
uvicorn[standard]==0.23.2
Setup Your FastAPI App for Vercel: In the project directory, update the code in a Python file,
main.py
. You will need to create a static folder and save a placeholderfavicon.ico
(Vercel looks for this file when deploying the API using the FastHTML Framework):
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
import os
app = FastAPI()
# Path to the favicon.ico file
favicon_path = os.path.join(os.path.dirname(__file__), "static", "favicon.ico")
# Mount the "static" directory
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
return FileResponse(favicon_path)
@app.get("/")
async def root():
return {"Hello": "World"}
Add a
vercel.json
Configuration File: Create avercel.json
file to define the entry point and runtime settings.
{
"builds": [
{
"src": "main.py",
"use": "@vercel/python"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "main.py"
}
]
}
This configuration tells Vercel that your application uses the @vercel/python
runtime and that the main API logic is in main.py
.
This is how the final directory structure being pushed to Git should look:
fastapi-vercel/
├── api/
│ └── main.py
├── static/
│ └── favicon.ico
├── requirements.txt
└── vercel.json
Push Code to GitHub
Vercel deploys the project on GitHub, so you need to push your FastAPI project to a GitHub repository.
Initialize Git: If your project is not yet under version control, initialize a Git repository:
git init
[Optional] Create a
.gitignore
File: Create a.gitignore
file to exclude unnecessary files like virtual environments:
__pycache__/
*.pyc
*.pyo
.env
Push to GitHub: Create a new private GitHub repository and push your code. Vercel allows you to keep your app’s source code private.
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/<your-username>/<your-repo-name>.git
git push -u origin master
To learn how to set up GitHub repositories, you can watch this tutorial.
Deploy on Vercel
Once your code is on GitHub, follow these steps to deploy it on Vercel:
Connect Vercel to GitHub:
Go to Vercel, login, and click "New Project."
Select "Import Git Repository" and connect your GitHub account.
Find and select the
fastapi-vercel
repository that contains your FastAPI project.
Configure and Deploy:
Choose the project name.
Under “Framework Preset” select “FastHTML” (if it has not been automatically chosen already).
Vercel will automatically detect your
requirements.txt
andvercel.json
files and configure the deployment.Review the settings and click “Deploy.”
Wait for Deployment:
Vercel will start the deployment process, and your FastAPI app will be live within a few seconds.
Once deployed, Vercel will provide a public URL where your API is accessible. You can visit it to see your FastAPI "Hello World" response.
For example https://fastapi-101.vercel.app/
Test Your FastAPI Deployment
Once the deployment is live, you can test it by visiting the public URL Vercel provides:
You should see the JSON response.
Additionally, you can check the auto-generated API documentation for your FastAPI project at:
Swagger UI: https://fastapi-101.vercel.app/docs
Conclusion
Congratulations! You’ve successfully deployed your FastAPI application on Vercel. By leveraging Vercel’s serverless platform, you’ve hosted a high-performance Python API for free, ideal for small projects, startups, or rapid prototyping.
Curious to explore more?
Check out my EncryptMe side project, where both the frontend and backend are hosted on Vercel for free. EncryptMe is a service that allows you to easily encrypt and decrypt messages, ensuring your private communications stay secure.
With your FastAPI app live, you can expand its functionality—add more routes, integrate databases, or even expose machine learning models through APIs. The possibilities are endless.
Happy coding!
Have you deployed your own FastAPI app?
Share your experience in the comments or reach out with any questions!