
Deploying a Flask API on Vercel is quick and efficient. Vercel provides serverless deployment with seamless scaling for your Python applications. In this guide, we’ll walk you through deploying a simple Flask API using Vercel's configuration.
Install Env Package: Make sure you installed python-dotenv or any similar package:
pip install python-dotenvEnvironment Setup: setup your .env file for production environment:
SERVER_HOST=<server-ip/domain>
SERVER_PORT=0.0.0.0In your app.py, you need to add the environment variables and ensure your app runs without any errors in the local setup.
from flask import Flask, jsonify
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
SERVER_HOST = os.getenv("SERVER_HOST")
SERVER_PORT = os.getenv("SERVER_PORT")
@app.route("/api/route", methods=["POST"])
def api_route():
return jsonify({"message": "API is running"}), 200
if __name__ == "__main__":
app.run(debug=True, host=SERVER_HOST, port=SERVER_PORT)Install Dependencies: Create a requirements.txt file with the following content:
pip install -r requirements.txtCreate vercel.json Configuration: Add a file named vercel.json in the root of your project with the following content:
{
"version": 2,
"builds": [
{
"src": "app.py",
"use": "@vercel/python"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "app.py"
}
]
}builds: Defines how to build the application.
routes: Ensures all incoming requests are routed to app.py
Install the Vercel CLI: If you haven’t already, install the Vercel CLI globally
npm install -g vercelLog In to Vercel: Authenticate using the Vercel CLI:
vercel loginInitialize Your Project: In your project directory, run:
vercel initFollow the prompts to:
Deploy to Vercel: Run the following command to deploy your Flask app:
vercel deployOr, you can deploy normally (skip step 3) by simply connecting your GitHub repository to the project and deploy! 🚀
Important: Make sure you add Environment Variables in Vercel and that's it. 😎