Skip to content

[Feature] Allow Passing Custom FastAPI Instance To openbb-api From File #7016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 44 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
062c9b8
allow passing custom fastapi instance to openbb-api command line laun…
deeleeramone Feb 2, 2025
4100c5b
lint
deeleeramone Feb 2, 2025
5147395
more lint
deeleeramone Feb 2, 2025
87d0697
more lint
deeleeramone Feb 2, 2025
257b440
Merge branch 'develop' into feature/launch-custom-backend
deeleeramone Feb 2, 2025
0bd438c
fix reading list from command line args for --exclude
deeleeramone Feb 2, 2025
75e494f
Merge branch 'feature/launch-custom-backend' of https://github.com/Op…
deeleeramone Feb 2, 2025
843c572
fix category and subCategory not populating by default
deeleeramone Feb 2, 2025
830216c
unused local
deeleeramone Feb 2, 2025
257b227
toml and lock cleanup
deeleeramone Feb 2, 2025
409c000
mock_widgets.json
deeleeramone Feb 2, 2025
2671f0b
add --templates-path arg
deeleeramone Feb 2, 2025
70af037
some path handling for templates
deeleeramone Feb 2, 2025
b3fcb75
add the middleware if it is just a plain FastAPI app being passed
deeleeramone Feb 2, 2025
328616c
mock_widgets.json
deeleeramone Feb 2, 2025
92d8e46
fix source as 'custom' when it is a provider
deeleeramone Feb 3, 2025
33d81d4
clean that up
deeleeramone Feb 3, 2025
79f6ef4
only use results for properties if it exists
deeleeramone Feb 3, 2025
02bd1b3
else instead of elif
deeleeramone Feb 3, 2025
b1a196f
lint
deeleeramone Feb 3, 2025
35d9e4b
update
deeleeramone Feb 3, 2025
c88a1d9
add a few default templates
deeleeramone Feb 3, 2025
468ef38
move order of events around or templates
deeleeramone Feb 4, 2025
a823dcb
update mock_widgets.json for runButton
deeleeramone Feb 4, 2025
a40ed0e
remove extra slash at beginning of route
deeleeramone Feb 4, 2025
24337d3
the real default templates..
deeleeramone Feb 4, 2025
742e373
undo black formatting to remove changes to router
deeleeramone Feb 4, 2025
166d2f8
fix retail_prices choices
deeleeramone Feb 4, 2025
24fdfee
fred cpi
deeleeramone Feb 4, 2025
6e7e020
put cpi beside pce
deeleeramone Feb 4, 2025
d35b44e
update readme
deeleeramone Feb 4, 2025
74c15b3
generate columnsDefs for non-platform apps and routers if output is a…
deeleeramone Feb 4, 2025
f7309e9
update readme
deeleeramone Feb 4, 2025
dc58fd8
typo
deeleeramone Feb 4, 2025
f84c9db
readme unused imports
deeleeramone Feb 4, 2025
837fb01
add a sentence to readme
deeleeramone Feb 4, 2025
4dc7cdf
update mock_widgets.json
deeleeramone Feb 5, 2025
44ecc2f
fix indentation
deeleeramone Feb 5, 2025
0674d21
make runButton False and fix a missing definition in yfinance management
deeleeramone Feb 6, 2025
92de210
duplicate comment
deeleeramone Feb 6, 2025
3ad85ab
read each Field in Query and Data for x-widget_config in json_schema_…
deeleeramone Feb 7, 2025
5fb2594
ruff
deeleeramone Feb 7, 2025
36f16f5
parameter placeholder label as Title
deeleeramone Feb 7, 2025
d1fa594
fix test
deeleeramone Feb 7, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 146 additions & 14 deletions openbb_platform/extensions/platform_api/README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,156 @@
# OpenBB Platform API Meta Package

This is a meta package for installing a command line script to launch the OpenBB Platform API, and the OpenBB Terminal Pro data connector widgets build script.
This package is responsible for launching and configuring an OpenBB Platform environment, or FastAPI instance, to use as an OpenBB Workspace custom backend.

## Installation

Install this package within an existing [OpenBB Platform Python environment](https://docs.openbb.co/platform/installation).
This package is included when you run [`pip install openbb`](https://docs.openbb.co/platform/installation); however, it also works as a standalone package
for creating new backends that are not part of the OpenBB GitHub [repository](https://github.com/OpenBB-finance/OpenBB/).

To install as a standalone, use a Python environment between versions 3.9 and 3.12, inclusively.

```sh
pip install openbb-platform-api
```

## Usage

The script is run from the command line, with the environment active, by entering:
See the [keyword arguments](#keyword-arguments) section for parameters and descriptions.

```sh
### Launch OpenBB Platform

To start the OpenBB Platform API, open a terminal, activate the environment where it is installed, and then enter:

```
openbb-api
```

This will launch a Fast API instance, via `uvicorn`, at `http://127.0.0.1:6900`

### Keyword Arguments
Uvicorn can be configured by adding keyword arguments, see the section [below](#keyword-arguments)

### Launch Custom App

To run your application as an OpenBB Workspace custom backend, add the path to the Python file with the FastAPI instance to the launch command.

```sh
openbb-api --app /Users/some_user/path/to/main.py
```

#### Example Application

This script will create a "markdown" widget with the returned text.

```python
from openbb_platform_api.main import app

@app.get("/hello")
async def hello() -> str:
"""Widget Description Generated By Docstring"""
return "Hello, from OpenBB!"
```

Function arguments will populate as widget parameters.

```python
from openbb_platform_api.main import app
from typing import Literal, Optional

@app.get("/hello")
async def hello(param1: Optional[str] = None, param2: Literal["Choice 1", "Choice 2"] = None, param3: bool = False) -> str:
"""Widget Description Generated By Docstring"""
if not param1 and not param2 and not param3:
return "Enter a parameter or make a choice!"
if param3:
return f"Param3 enabled!"
if param2:
return f"You selected: {param2}"
if param1:
return f"You entered: {param1}"

return "Nothing to return!"
```

Create a table widget by returning data shaped as a list of dictionaries (records)

```python
from openbb_platform_api.main import app

@app.get("/hello")
async def hello() -> list:
"""Widget Description Generated By Docstring"""
return [{"Column 1": "Hello", "Column 2": "from OpenBB!"}]
```

#### Widget Config

Any value from the [`widgets.json`](https://docs.openbb.co/terminal/custom-backend/widgets.json) structure can be passed into the `@app` decorator by including an `openapi_extra` dictionary with the key, `"widget_config"`.

```python
from openbb_platform_api.main import app


@app.get("/hello",
openapi_extra={
"widget_config": {
"data": {
"table": {
"columnsDefs": [
{"field": "Column 1", "headerName": "My Column", "headerTooltip": "Tooltip added!", "type": "text"}
]
}
}
}
}
)
async def hello() -> list:
"""Widget Description Generated By Docstring"""
return [{"Column 1": "Hello", "Column 2": "from OpenBB!"}]
```

Configurations for `widgets.json` supplied here will override any of the automatically generated content.
If the key does not exist, it will be created.

#### Auto-Generate ColumnsDefs

To generate ColumnsDefs for each field in the response data, return a list of Pydantic models with each column being assigned to Field.

Inherit the BaseModel from the `openbb-core` package by using the imports below.

Columns, by default, are presented in the order of insertion.

```python
from openbb_platform_api.main import app
from openbb_core.provider.abstract.data import Data # Inherit this instead of pydantic.BaseModel to represent 1 row of data.
from pydantic import Field

class MyData(Data):
"""MyData Response Model."""
column_1: str = Field(title="Column 1", description="Description for Column 1") # 'description' will add the column header tooltip to your widget.
column_2: str = Field(title="Column 2", description="Description for Column 2")


@app.get("/hello")
async def hello() -> list[MyData]:
"""Widget Description Generated By Docstring"""
return [MyData.model_validate({"column_1": "Hello", "column_2": "from OpenBB!"})]
```

## Keyword Arguments

The behavior of the script can be configured with the use of arguments and keyword arguments.

Launcher specific arguments:

--build Build the widgets.json file.
--no-build Do not build the widgets.json file.
--app Absolute path to the Python file with the target FastAPI instance. Default is the installed OpenBB Platform API.
--editable Flag to make widgets.json an editable file that can be modified during runtime. Default is 'false'.
--build If the file already exists, changes prompt action to overwrite/append/ignore. Only valid when --editable true.
--no-build Do not build the widgets.json file. Use this flag to load an existing widgets.json file without checking for updates.
--login Login to the OpenBB Platform.
--no-filter Do not filter the widgets.json file.

--exclude JSON encoded list of API paths to exclude from widgets.json. Disable entire routes with '*' - e.g. '["/api/v1/*"]'.
--no-filter Do not filter out widgets in widget_settings.json file.
--widgets-path Absolute path to the widgets.json file. Default is ~/envs/{env}/assets/widgets.json. Supplying this sets --editable true.
--templates-path Absolute path to the workspace_templates.json file. Default is ~/OpenBBUserData/workspace_templates.json.

All other arguments will be passed to uvicorn. Here are the most common ones:

Expand Down Expand Up @@ -81,29 +201,41 @@ Contact the system administrator if you are using a work device and require addi

### Location of `widgets.json`

An OpenBB Terminal Pro data connector requires a file, `widgets.json`, to be served by the API. It contains the configuration for each widget available to be added to a dashboard. The file is stored, and served from, the environment's assets folder.
When launched as `openbb-api --editiable`, a file will be stored to disk. By default, that location is:

```sh
/Path/to/environments/envs/obb/assets/widgets.json
```

It can be manually edited and served without the build process by passing `--no-build` to the API launch script.
The file can be manually edited and served without the build process by passing `--editable --no-build` to the API launch script.

```sh
openbb-api --no-build
openbb-api --editable --no-build
```

If you would like to construct this file manually for a custom backend configuration, save the file in the path above.
If you would like to construct this file manually, create the file and define the path as an argument.

```sh
openbb-api --widgets-path /Users/some_user/path/to/widgets.json
```


### Location of `templates.json`

By default, the location is:

> ~/OpenBBUserData/workspace_templates.json

This can be changed by adding the path as an argument.

```sh
openbb-api --templates-path /Users/some_user/path/to/workspace_templates.json
```

The OpenBB Workspace allows you to export the current dashboard layout - when it is a custom backend - as a template.

To export the layout, right-click on the dashboard and select, "Export Template".

A JSON dictionary will be exported. Insert the contents of the export into "~/OpenBBUserData/workspace_templates.json" by pasting between the JSON list markers, [ ].

If there is more than one, add a comma to the closing curly brace, }.
If there are more than one, add a comma between each dictionary entry.
Loading