Running Panel apps in FastAPI
Panel generally runs on the Bokeh server, which itself runs on Tornado. However, it is also often useful to embed a Panel app in an existing web application, such as a FastAPI web server.
Since Panel 1.5.0 it is possible to run Panel application(s) natively on a FastAPI based server. Therefore this how-to guide will explain how to add Panel application(s) directly to an existing FastAPI application. This functionality is new and experimental so we also provide the original how-to guide to embed a Tornado based Panel server application inside a FastAPI application.
By the end of this guide, you'll be able to run a FastAPI application that serves a simple interactive Panel app. The Panel app will consist of a slider widget that dynamically updates a string of stars (⭐) based on the slider's value.
Setup
Following FastAPI's Tutorial - User Guide make sure you first have FastAPI and bokeh-fastapi installed using:
::::{tab-set}
:::{tab-item} pip
:::
:::{tab-item} conda
:::
::::
Create a FastAPI application
Start by creating a FastAPI application. In this application, we will define a root endpoint that returns a simple JSON response. Open your text editor or IDE and create a file named main.py:
Create a Panel Application
Next we will define a simple Panel application that allows you to control the number of displayed stars with an integer slider and decorate it with the add_panel_app
decorator:
That's it! This decorator will map a specific URL path to the Panel app, allowing it to be served as part of the FastAPI application.
The complete file should now look something like this:
Now run it with:
You should see the following output:
If you visit http://127.0.0.1:8000
you will see the Panel application.
Adding multiple applications
The add_application
decorator is useful when server an application defined in a function, if you want to serve multiple applications, whether they are existing Panel objects, functions, or paths to Panel application scripts you can use the add_applications
function instead, e.g.:
Tips & Tricks
Running Behind a Proxy
In some cases, you might be running your FastAPI app behind a reverse proxy, which adds an extra path prefix that your application doesn't directly handle. This is common when working in environments like JupyterHub or deploying to Kubernetes.
For instance, if your FastAPI /
endpoint is accessed at https://some.domain/some/path/
, you will need to specify the path prefix when starting your FastAPI server. To do this, use the flag --root-path /some/path/
. This ensures you can access the OpenAPI docs at https://some.domain/some/path/docs
.
For more details, refer to the Behind a Proxy guide.
Conclusion
That's it! You now have embedded panel in FastAPI! You can now build off of this to create your own web app tailored to your needs.