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

Conversation

deeleeramone
Copy link
Contributor

@deeleeramone deeleeramone commented Feb 2, 2025

  1. Why?:

    • This dramatically reduces the amount of boiler plate code required to create your own custom backend data connection for the OpenBB Workspace, and associated widgets.
  2. What?:

    • Extends some of the launch arguments and changes some default behavior to eliminate any command-line user input prompts for default configurations.

Everything from widgets.json can be entered directly to the openapi_extra dictionary. This can be used to add, or override, anything automatically generated from reading openapi.json.

app.get("/some_route", openapi_extra={"widget_config": {})
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.
  1. Impact:

    • Get started with 1 python package install (will be 1 when next openbb-core is released), 1 python file, and 4 lines of code.
Screenshot 2025-01-31 at 11 19 06 PM

You can annotate your function query and response models normally, and that helps generate widgets.json.

from typing import Annotated
from fastapi import FastAPI, Query
from openbb_core.provider.abstract.data import Data
from pydantic import Field

app = FastAPI()


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


class MyData(Data):
    """MyData Response Model."""

    column_1: str = Field(title="Some Text", description="Hover text for Column 1")
    column_2: int = Field(
        title="Some Number",
        description="Hover text for Column 2",
        json_schema_extra={"x-widget_config": {"cellDataType": "text"}},
    )
    column_3: float = Field(
        title="Some Percent",
        description="Hover text for Column 3",
        json_schema_extra={"x-unit_measurement": "percent"},
    )
    column_4: float = Field(
        title="Some Normalized Percent",
        description="Hover text for Column 4",
        json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
    )


@app.get(
    "/table",
)
async def table(
    param1: Annotated[
        str,
        Query(
            description="Hover text for param1",
            title="Placeholder",
        ),
    ] = None,
    param2: Annotated[
        int, Query(description="Some Number", title="Placeholder")
    ] = None,
    date: Annotated[
        str,
        Query(
            description="Date selector",
            json_schema_extra={"x-widget_config": {"value": "$currentDate-1w"}},
        ),
    ] = None,
) -> list[MyData]:
    """Widget Description Generated By Docstring"""
    return [
        MyData.model_validate(
            {
                "column_1": "Hello",
                "column_2": 10,
                "column_3": 33.345,
                "column_4": -0.33345,
            }
        ),
    ]
Screenshot 2025-02-07 at 3 12 36 PM
  1. Testing Done:

In a fresh environment, install these extensions in develop mode:

  • /openbb_platform/core
  • /openbb_platform/extensions/platform_api

Make some Python file, and then run it with:

openbb-api --app /Users/me/path/to/file/main.py
from openbb_platform_api.main import app
from openbb_core.provider.utils.helpers import get_requests_session

session = get_requests_session()


@app.get(
    "/crypto/defi/defi_llama_protocol_details",
    openapi_extra={"widget_config": {"name": "Defi Llama Protocol Details"}},
)
def defi_llama_protocol_details(protocol_id: str = None) -> str:  # defining this as a str output automatically sets the widget to 'markdown'
    """Get details for a given protocol using Defi Llama"""
    data = session.get(f"https://api.llama.fi/protocol/{protocol_id}")

    if data.status_code == 200:
        data = data.json()
    else:
        return data.text

    github_links = ""
    if "github" in data and data["github"]:
        github_links = "**GitHub:** " + ", ".join(data["github"])

    # Use HTML for multi-column layout
    logo = data.get("logo")
    name = data.get("name", "N/A")
    description = data.get("description", "N/A")
    website = data.get("url", "N/A")

    md = (
        f"{name} Logo: ![Logo]({logo})\n\n"
        f"**Description:** {description}\n\n"
        f"## X\n\n"
        f"**X:** {data.get('twitter', 'N/A')}\n\n"
        "## Links\n"
        f"**Website:** {website}\n\n"
        f"{github_links}"
    )
    return md
Screenshot 2025-02-01 at 5 40 59 PM

Screenshot 2025-01-31 at 7 34 50 PM

Screenshot 2025-02-04 at 2 53 49 PM

@github-actions github-actions bot added enhancement Enhancement platform OpenBB Platform v4 PRs for v4 labels Feb 2, 2025
@deeleeramone deeleeramone requested a review from piiq February 3, 2025 18:24
@deeleeramone deeleeramone requested a review from jmaslek February 4, 2025 17:48
@piiq piiq added this pull request to the merge queue Feb 10, 2025
Merged via the queue into develop with commit aa84443 Feb 10, 2025
10 checks passed
@deeleeramone deeleeramone deleted the feature/launch-custom-backend branch February 12, 2025 00:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhancement platform OpenBB Platform v4 PRs for v4
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants