Skip to main content
Sometimes you might want to integrate Squirrels APIs into an existing FastAPI application rather than running Squirrels as a standalone server (i.e., using sqrl run). This allows you to serve your Squirrels datasets alongside other routes and services in your application.

Prerequisites

  • A Squirrels project already initialized and configured, with squirrels >= 0.6.0 installed.
  • An existing FastAPI application in Python.

Steps

1. Initialize SquirrelsProject and get components

First, you need to create an instance of SquirrelsProject pointing to your project directory and use it to retrieve the FastAPI components. We recommend using a with statement to ensure that the project is closed and its resources are released after use.
The host and port arguments are optional and only used for the welcome banner. Squirrels does not get to control or view the host and port of the API server - only uvicorn gets to control these. If not provided, the default values of localhost and 8000 are used.
The sqrl_server is a FastAPIComponents object that contains:
  • fastapi_app: The sub-app containing all the routes for your Squirrels datasets, dashboards, and authentication.
  • lifespan: The lifespan context manager that handles background tasks such as periodically refreshing parameter options from data sources.
  • mount_path: The mount path for the Squirrels sub-app.
By default, the mount path is /analytics/{project_name}/v{project_version}. You can specify the mount_path_format argument to customize the mount path with your own format while including the project name and version.Note that any underscores in the project name are replaced by dashes. For example, if the project name is “my_project” and the project version is “1”, then the mount_path value is /analytics/my-project/v1.

2. Integrate the lifespan

Create the FastAPI app with the Squirrels lifespan.
If you have defined your own lifespan function, you should include the Squirrels lifespan to ensure that Squirrels’ background tasks run correctly.

3. Mount the sub-app

Mount the Squirrels sub-app to your main FastAPI application at the mount path of the FastAPIComponents object.

Complete Example

Here is a complete example of a FastAPI application with a Squirrels project mounted.
Now, your Squirrels APIs will be available under the path sqrl_server.mount_path (e.g., http://localhost:8000/analytics/my-project/v1/api/0/...).