FastAPI Integration
FastAPI is a modern, high-performance Python web framework that’s perfect for building REST APIs with Genkit. This guide shows you how to integrate Genkit flows with FastAPI applications.
Before you begin
Section titled “Before you begin”You should be familiar with Genkit’s concept of flows, and how to write them.
Create a project
Section titled “Create a project”Create a new Python project with uv:
uv init my-genkit-appcd my-genkit-appInstallation
Section titled “Installation”Install FastAPI and Genkit dependencies:
uv add fastapi uvicorn genkit genkit-plugin-google-genaiDefine Genkit flows
Section titled “Define Genkit flows”Create a file for your Genkit flows, for example flows.py:
from genkit import Genkitfrom genkit.plugins.google_genai import GoogleAI
# Initialize Genkitai = Genkit( plugins=[GoogleAI()], model='googleai/gemini-2.5-flash',)
@ai.flow()async def menu_suggestion_flow(theme: str) -> str: """Generate a menu item for a themed restaurant.
Args: theme: The restaurant theme.
Returns: A suggested menu item. """ response = await ai.generate( prompt=f'Invent a menu item for a {theme} themed restaurant.', ) return response.textCreate FastAPI routes
Section titled “Create FastAPI routes”Create your FastAPI application and expose your flows as API endpoints:
from fastapi import FastAPIfrom pydantic import BaseModelfrom flows import menu_suggestion_flow
app = FastAPI()
class MenuRequest(BaseModel): theme: str
@app.post("/menuSuggestion")async def menu_suggestion(request: MenuRequest): """Generate a menu suggestion.""" result = await menu_suggestion_flow(request.theme) return {"menuItem": result}Call your flows from the client
Section titled “Call your flows from the client”You can call your FastAPI endpoints using any HTTP client:
import requests
response = requests.post( 'http://localhost:8000/menuSuggestion', json={'theme': 'pirate'})print(response.json())Authentication (Optional)
Section titled “Authentication (Optional)”Add authentication to your API routes using FastAPI’s dependency injection:
from fastapi import Depends, HTTPException, statusfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict: """Verify JWT token.""" token = credentials.credentials # Add your token verification logic here # Return user info or raise HTTPException return {"user_id": "123", "email": "user@example.com"}
@app.post("/menuSuggestion")async def protected_menu_suggestion( request: MenuRequest, user: dict = Depends(verify_token)): """Generate a menu suggestion with authentication.""" result = await menu_suggestion_flow(request.theme) return {"menuItem": result, "user": user["email"]}Run your application
Section titled “Run your application”Development
Section titled “Development”uv run uvicorn main:app --reloadWith Genkit Developer UI
Section titled “With Genkit Developer UI”genkit start -- uv run uvicorn main:app --reloadTest your app locally
Section titled “Test your app locally”Set up credentials for your model provider:
Gemini (Google AI)
export GEMINI_API_KEY=<your API key>uv run uvicorn main:app --reloadGemini (Vertex AI)
export GOOGLE_CLOUD_PROJECT=<your project ID>export GOOGLE_CLOUD_LOCATION=us-central1gcloud auth application-default loginuv run uvicorn main:app --reloadDeploy your app
Section titled “Deploy your app”When you deploy your app, you’ll need to make credentials available. See:
API Documentation
Section titled “API Documentation”FastAPI automatically generates interactive API documentation:
- Swagger UI: Visit
http://localhost:8000/docs - ReDoc: Visit
http://localhost:8000/redoc