{"id":9735,"library":"fastapi-profiler","title":"FastAPI Profiler","description":"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.","status":"active","version":"1.5.0","language":"en","source_language":"en","source_url":"https://github.com/sunhailin-Leo/fastapi_profiler","tags":["fastapi","profiling","middleware","performance","pyinstrument"],"install":[{"cmd":"pip install fastapi-profiler","lang":"bash","label":"Default Install"}],"dependencies":[{"reason":"Core framework for the middleware","package":"fastapi","optional":false},{"reason":"The underlying profiling engine","package":"pyinstrument","optional":false},{"reason":"Required for the browser-based HTML profile viewer","package":"Jinja2","optional":true}],"imports":[{"symbol":"FastAPIProfilerMiddleware","correct":"from fastapi_profiler import FastAPIProfilerMiddleware"}],"quickstart":{"code":"from fastapi import FastAPI\nfrom fastapi_profiler import FastAPIProfilerMiddleware\nimport uvicorn\nimport time\n\n# For local development, you might enable profiling via an env var (e.g., in a .env file)\n# PYINSTRUMENT_PROFILING_ENABLED=true\n\napp = FastAPI()\n\napp.add_middleware(\n    FastAPIProfilerMiddleware,\n    profiler_dir=\".\", # Directory to save profile reports (e.g., HTML files)\n    is_print_enable=True, # Print summary to console\n    profiler_sample_rate=0.1, # Profile only 10% of requests (v1.5.0+ feature)\n    always_profile_errors=True, # Always profile 5xx errors regardless of sample rate (v1.5.0+ feature)\n    # is_browser_enable=True, # Requires `pip install Jinja2` to view reports in browser\n    # html_file_name=\"profile_report.html\", # Custom HTML report filename\n    # log_format=\"json\", # v1.5.0+ for structured logging\n)\n\n@app.get(\"/\")\nasync def read_root():\n    time.sleep(0.05) # Simulate some work\n    return {\"message\": \"Hello FastAPI Profiler!\"}\n\n@app.get(\"/slow\")\nasync def read_slow():\n    time.sleep(0.2) # Simulate a slow operation\n    return {\"message\": \"This was a slow request!\"}\n\n# To run this application:\n# 1. Save the code as `main.py`\n# 2. Run from your terminal: `uvicorn main:app --reload`\n# 3. Access in your browser: http://127.0.0.1:8000/ or http://127.0.0.1:8000/slow\n#    Check your current directory for profile files (.html, .json, .prof) and console output.","lang":"python","description":"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."},"warnings":[{"fix":"In production, always set `profiler_sample_rate` to a low value (e.g., 0.01-0.1) or use environment variables like `PYINSTRUMENT_PROFILING_ENABLED=false` for a no-op. Consider `always_profile_errors=True` to catch performance issues only on failing requests. For long-term monitoring, integrate with structured logging.","message":"Running `fastapi-profiler` with `is_print_enable=True` or `is_browser_enable=True` (especially without `profiler_sample_rate`) in high-traffic production environments can introduce significant overhead or generate too many files. The profiler itself consumes CPU and I/O resources.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure `Jinja2` is installed explicitly if you intend to use `is_browser_enable=True` by running `pip install Jinja2` or `pip install fastapi-profiler[browser]`.","message":"The browser-based HTML report viewer functionality (`is_browser_enable=True`) requires the `Jinja2` package, which is an optional dependency. If not installed, enabling this feature will lead to runtime errors or silent failures.","severity":"gotcha","affected_versions":"All versions"},{"fix":"When upgrading to v1.5.0 or later, review your logging configuration. If you prefer the old text format, explicitly set `log_format='text'`. If migrating to JSON, update your log aggregation tools to parse the new structured output.","message":"The `log_format='json'` option, introduced in v1.5.0, changes the output format of request logs. If you rely on a specific log parsing setup that expects plain text, switching to JSON might break existing log ingestion pipelines.","severity":"gotcha","affected_versions":">=1.5.0"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Upgrade `fastapi-profiler` to version 1.4.1 or newer. This issue was addressed in the 1.4.1 release.","cause":"An older version of `fastapi-profiler` (<1.4.1) was incompatible with changes in FastAPI/Starlette's Request object structure, causing this error on certain requests.","error":"AttributeError: 'str' object has no attribute 'raw_headers'"},{"fix":"Install Jinja2 explicitly: `pip install Jinja2` or use the extra: `pip install fastapi-profiler[browser]`.","cause":"Attempting to use `is_browser_enable=True` in `FastAPIProfilerMiddleware` without installing the optional `Jinja2` dependency.","error":"ModuleNotFoundError: No module named 'Jinja2'"},{"fix":"Ensure the directory specified by `profiler_dir` has write permissions. Check if `PYINSTRUMENT_PROFILING_ENABLED` is not explicitly set to 'false' in your environment. If using `profiler_sample_rate`, increase its value (e.g., to 1.0 for debugging) to ensure requests are profiled. Make sure requests are actually hitting the FastAPI app with the middleware.","cause":"The `profiler_dir` is not writable, the `PYINSTRUMENT_PROFILING_ENABLED` environment variable is set to 'false', or `profiler_sample_rate` is too low (or 0.0) for the requests being made.","error":"Profiler report files are not being generated in the specified directory."}]}