FastAPI Profiler

1.5.0 · active · verified Fri Apr 17

fastapi-profiler is a FastAPI Middleware that integrates pyinstrument to provide request profiling and performance analysis for FastAPI applications. It helps developers identify bottlenecks by generating detailed reports (HTML, speedscope, JSON, .prof files). As of version 1.5.0, it supports sampling, error auto-capture, and structured JSON logging. It generally follows a regular release cadence, with several minor releases a year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `FastAPIProfilerMiddleware` into a FastAPI application, configure basic profiling options, and simulate a slow endpoint. It highlights saving profiles to disk, printing summaries to console, and using new features like sampling and error auto-capture. Run the app with Uvicorn and access endpoints to generate profiles.

from fastapi import FastAPI
from fastapi_profiler import FastAPIProfilerMiddleware
import uvicorn
import time

# For local development, you might enable profiling via an env var (e.g., in a .env file)
# PYINSTRUMENT_PROFILING_ENABLED=true

app = FastAPI()

app.add_middleware(
    FastAPIProfilerMiddleware,
    profiler_dir=".", # Directory to save profile reports (e.g., HTML files)
    is_print_enable=True, # Print summary to console
    profiler_sample_rate=0.1, # Profile only 10% of requests (v1.5.0+ feature)
    always_profile_errors=True, # Always profile 5xx errors regardless of sample rate (v1.5.0+ feature)
    # is_browser_enable=True, # Requires `pip install Jinja2` to view reports in browser
    # html_file_name="profile_report.html", # Custom HTML report filename
    # log_format="json", # v1.5.0+ for structured logging
)

@app.get("/")
async def read_root():
    time.sleep(0.05) # Simulate some work
    return {"message": "Hello FastAPI Profiler!"}

@app.get("/slow")
async def read_slow():
    time.sleep(0.2) # Simulate a slow operation
    return {"message": "This was a slow request!"}

# To run this application:
# 1. Save the code as `main.py`
# 2. Run from your terminal: `uvicorn main:app --reload`
# 3. Access in your browser: http://127.0.0.1:8000/ or http://127.0.0.1:8000/slow
#    Check your current directory for profile files (.html, .json, .prof) and console output.

view raw JSON →