Building and Deploying FastAPI Applications to Vercel
Getting Started with FastAPI
FastAPI is a modern, fast, and powerful Python web framework for building backend API applications. It boasts an impressive set of features, including API documentation powered by Swagger, security modules, and type checking to ensure code correctness. To follow along, you’ll need a basic understanding of Python, Git, and a Postman or virtualenv installation on your machine. Additionally, create a Vercel account to deploy your application.
Building a Simple Notes App
To demonstrate the deployment process, we’ll build a simple notes app. Start by creating a project folder and installing the necessary dependencies using virtualenv. Next, activate the virtual environment and install FastAPI and Uvicorn, an ASGI server that enables us to run our application.
pip install fastapi uvicorn
Defining the Model Schema
In the model.py
file, define a Pydantic schema called NoteSchema
, which represents how notes data will be stored in our application’s temporary database. This schema will guide users when sending requests from the interactive docs.
from pydantic import BaseModel
class NoteSchema(BaseModel):
id: int
title: str
content: str
Defining Routes for CRUD Operations
In the routes.py
file, create an in-app database to store and retrieve notes, and import the NoteSchema
. Define routes for GET requests, including a route to return all available notes and a route to return a note with a matching ID.
from fastapi import FastAPI, HTTPException
from model import NoteSchema
app = FastAPI()
notes_db = []
@app.get("/notes/")
async def read_notes():
return notes_db
@app.get("/notes/{note_id}")
async def read_note(note_id: int):
for note in notes_db:
if note["id"] == note_id:
return note
raise HTTPException(status_code=404, detail="Note not found")
Testing Routes
Test the routes using Postman or Insomnia, sending GET requests to retrieve notes and POST requests to add new notes. Define update and delete routes, performing partial updates and deleting notes only if they exist.
@app.post("/notes/")
async def create_note(note: NoteSchema):
notes_db.append(note.dict())
return note
@app.put("/notes/{note_id}")
async def update_note(note_id: int, note: NoteSchema):
for i, n in enumerate(notes_db):
if n["id"] == note_id:
notes_db[i] = note.dict()
return note
raise HTTPException(status_code=404, detail="Note not found")
@app.delete("/notes/{note_id}")
async def delete_note(note_id: int):
for i, n in enumerate(notes_db):
if n["id"] == note_id:
del notes_db[i]
return {"message": "Note deleted"}
raise HTTPException(status_code=404, detail="Note not found")
Deploying to Vercel
To deploy your application to Vercel, create a vercel.json
configuration file and add the necessary JSON code. This file specifies the path to the application’s entry point and the package to use when building the app. Create a requirements.txt
file containing your application dependencies and initialize Vercel using the command line tool.
{
"version": 2,
"builds": [
{
"src": "main.py",
"use": "@vercel/python"
}
]
}
pip freeze > requirements.txt
Previewing the Deployed Application
Follow the prompts in the console, and you’ll see a similar screen indicating a successful deployment. Preview the deployed application by clicking the links in the console or from your Vercel dashboard.
What’s Next?
In this article, we’ve learned how to build and deploy a FastAPI application to Vercel. To dive deeper into FastAPI, explore the official documentation and access the code used in this article on GitHub.