Files
OpenBB/openbb_platform/extensions/platform_api

OpenBB Platform API Meta Package

This package is responsible for launching and configuring an OpenBB Platform environment, or FastAPI instance, to use as an OpenBB Workspace custom backend.

Installation

This package is included when you run pip install openbb; however, it also works as a standalone package for creating new backends that are not part of the OpenBB GitHub repository.

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

pip install openbb-platform-api

Usage

See the keyword arguments section for parameters and descriptions.

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

Uvicorn can be configured by adding keyword arguments, see the section below

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.

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

Example Application

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

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.

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)

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 structure can be passed into the @app decorator by including an openapi_extra dictionary with the key, "widget_config".

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.

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:

--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.
--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:

--host TEXT                     Host IP address or hostname.
                                  [default: 127.0.0.1]
--port INTEGER                  Port number.
                                  [default: 6900]
--ssl-keyfile TEXT              SSL key file.
--ssl-certfile TEXT             SSL certificate file.
--ssl-keyfile-password TEXT     SSL keyfile password.
--ssl-version INTEGER           SSL version to use.
                                  (see stdlib ssl module's)
                                  [default: 17]
--ssl-cert-reqs INTEGER         Whether client certificate is required.
                                  (see stdlib ssl module's)
                                  [default: 0]
--ssl-ca-certs TEXT             CA certificates file.
--ssl-ciphers TEXT              Ciphers to use.
                                  (see stdlib ssl module's)
                                  [default: TLSv1]

Run uvicorn --help to get the full list of arguments.

API Over HTTPS

To run the API over the HTTPS protocol, you must first create a self-signed certificate and the associated key. After activating the environment, you can generate the files by entering this to the command line:

openssl req -x509 -days 3650 -out localhost.crt -keyout localhost.key   -newkey rsa:4096 -nodes -sha256   -subj '/CN=localhost' -extensions EXT -config <( \
   printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

Two files will be created, in the current working directory, that are passed as keyword arguments to the openbb-api entry point.

openbb-api --ssl_keyfile localhost.key --ssl_certfile localhost.crt

Note: Adjust the command to include the full path to the file if the current working directory is not where they are located.

The certificate - localhost.crt - will need to be added to system's trust store. The process for this will depend on the operating system and the user account privilege.

A quick solution is to visit the server's URL, show the details of the warning, and choose to continue anyways.

Contact the system administrator if you are using a work device and require additional permissions to complete the configuration.

This Connection Is Not Private

Location of widgets.json

When launched as openbb-api --editiable, a file will be stored to disk. By default, that location is:

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

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

openbb-api --editable --no-build

If you would like to construct this file manually, create the file and define the path as an argument.

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.

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 are more than one, add a comma between each dictionary entry.