Python Functions in the /api Directory
Vercel supports existing projects that define file-based Python functions in
an /api directory. File-based Python functions map .py files to routes and
load ASGI applications, WSGI applications, or BaseHTTPRequestHandler
subclasses.
For new Python applications, use a framework preset for FastAPI, Flask, or Django. To run a Python backend alongside another framework, use Services.
Without a detected Python framework preset, each .py file inside /api
becomes a separate Vercel Function. Vercel serves each function at its file
path. For example, api/index.py serves /api, and api/users.py serves
/api/users.
Each .py file must define one of these top-level names:
appfor an ASGI or WSGI applicationapplicationfor a WSGI applicationhandlerfor a class that inherits fromBaseHTTPRequestHandler
The following function uses BaseHTTPRequestHandler:
from http.server import BaseHTTPRequestHandler
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write('Hello, world!'.encode('utf-8'))A Python framework preset takes precedence over file-based functions. When
Vercel detects a framework preset, the framework application handles all
requests, and files under /api don't become separate Vercel Functions.
Use the functions property
in vercel.json to configure file-based Python functions. For example, use
excludeFiles to exclude files that the functions don't need at runtime:
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"functions": {
"api/**/*.py": {
"excludeFiles": "{tests/**,__tests__/**,**/*.test.py,**/test_*.py,fixtures/**,__fixtures__/**,testdata/**,sample-data/**,static/**,assets/**}"
}
}
}For dependency files, Python versions, streaming, bundle size limits, and file system behavior, see the Python runtime reference.
Was this helpful?