{"id":22352837,"url":"https://github.com/jrycw/gt-fastapi","last_synced_at":"2026-02-04T07:09:48.681Z","repository":{"id":253394687,"uuid":"843367793","full_name":"jrycw/gt-fastapi","owner":"jrycw","description":"Great Tables running in FastAPI","archived":false,"fork":false,"pushed_at":"2024-10-03T13:57:51.000Z","size":126,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-07T13:43:14.308Z","etag":null,"topics":["fastapi","pandas","polars","python","tables"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jrycw.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-16T11:09:04.000Z","updated_at":"2025-02-01T19:02:28.000Z","dependencies_parsed_at":"2024-09-10T14:31:24.847Z","dependency_job_id":"edbdc329-1f32-41fb-8e2a-905333c20898","html_url":"https://github.com/jrycw/gt-fastapi","commit_stats":null,"previous_names":["jrycw/gt-fastapi"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jrycw/gt-fastapi","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jrycw%2Fgt-fastapi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jrycw%2Fgt-fastapi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jrycw%2Fgt-fastapi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jrycw%2Fgt-fastapi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jrycw","download_url":"https://codeload.github.com/jrycw/gt-fastapi/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jrycw%2Fgt-fastapi/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265026167,"owners_count":23699903,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastapi","pandas","polars","python","tables"],"created_at":"2024-12-04T12:28:01.954Z","updated_at":"2026-02-04T07:09:48.655Z","avatar_url":"https://github.com/jrycw.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gt-fastapi\n\n### Introduction\n\nThis guide will walk you through setting up a FastAPI application that renders a table using the `GT` library.\n\n### Steps\n\n1. **Create a FastAPI App Instance**\n\n   Start by creating an instance of the FastAPI app:\n\n   ```python\n   app = FastAPI()\n   ```\n\n2. **Create the `index` Endpoint**\n\n    Define the `index` endpoint, which will generate an HTML table using `GT.as_raw_html()` and return it via `templates.TemplateResponse` when users visit the `/` route:\n\n   ```python\n    @cache\n    def get_sza():\n        return pl.from_pandas(sza)\n\n\n    @app.get(\"/\", response_class=HTMLResponse)\n    async def index(request: Request):\n        sza_pivot = (\n            get_sza()\n            .filter((pl.col(\"latitude\") == \"20\") \u0026 (pl.col(\"tst\") \u003c= \"1200\"))\n            .select(pl.col(\"*\").exclude(\"latitude\"))\n            .drop_nulls()\n            .pivot(values=\"sza\", index=\"month\", on=\"tst\", sort_columns=True)\n        )\n\n        sza_gt = (\n            GT(sza_pivot, rowname_col=\"month\")\n            .data_color(\n                domain=[90, 0],\n                palette=[\"rebeccapurple\", \"white\", \"orange\"],\n                na_color=\"white\",\n            )\n            .tab_header(\n                title=\"Solar Zenith Angles from 05:30 to 12:00\",\n                subtitle=html(\"Average monthly values at latitude of 20\u0026deg;N.\"),\n            )\n            .sub_missing(missing_text=\"\")\n        )\n\n        context = {\"sza_gt\": sza_gt.as_raw_html()}\n\n        return templates.TemplateResponse(\n            request=request, name=\"index.html\", context=context\n        )\n   ```\n\n3. **Set Up the Template**\n\n   Create a `templates` directory and an `index.html` file within it. This file will render the HTML table generated by the `index` endpoint. Be sure to use the `safe` template tag to prevent Jinja from escaping the HTML:\n\n   ```html\n   \u003c!DOCTYPE html\u003e\n   \u003chtml lang=\"en\"\u003e\n     \u003chead\u003e\n       \u003cmeta charset=\"UTF-8\"\u003e\n       \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n       \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n       \u003ctitle\u003eFastAPI-GT Website\u003c/title\u003e\n     \u003c/head\u003e\n     \u003cbody\u003e\n       \u003cmain\u003e\n           \u003ch1 style=\"text-align:center\"\u003eGreat Tables shown in FastAPI\u003c/h1\u003e  \n       \u003c/main\u003e\n       \u003cdiv\u003e\n           {{ sza_gt | safe }}\n       \u003c/div\u003e\n     \u003c/body\u003e\n   \u003c/html\u003e\n   ```\n\n4. **Run the Uvicorn Server**\n\n   Finally, start the Uvicorn server and open your browser to view the rendered table:\n\n   ```bash\n   uvicorn main:app --reload\n   ```\n   \nYou should now see the table displayed in your browser at http://127.0.0.1:8000.\n\n![table](https://raw.githubusercontent.com/jrycw/gt-fastapi/refs/heads/master/gt-fastapi.png)\n\n### Alternative steps\nAlternatively, you could use the decorator approach to avoid calling `GT.as_raw_html()` for each `GT` instance. However, I'm unsure if this method is actually easier for developers. \n\n**Please note that the `gt2fastapi` decorator is for demonstration purposes only and is not fully implemented. You will also need to handle additional information, such as [status codes, headers, media types, and background tasks](https://fastapi.tiangolo.com/reference/templating/?h=templatere#fastapi.templating.Jinja2Templates.TemplateResponse)**.\n\n```python\nimport inspect\nfrom functools import cache, partial, wraps\n\nimport polars as pl\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom great_tables import GT, html\nfrom great_tables.data import sza\n\napp = FastAPI()\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\n\n@cache\ndef get_sza():\n    return pl.from_pandas(sza)\n\n\ndef gt2fastapi(func=None):\n    \"\"\"\n    https://pybit.es/articles/decorator-optional-argument/\n    \"\"\"\n\n    def _get_template_response(resp):\n        context = resp.context\n        request = context.pop(\"request\")\n        name = resp.template.name\n        new_context = {}\n        for key, value in context.items():\n            if isinstance(value, GT):\n                value = value.as_raw_html()\n            new_context[key] = value\n        return templates.TemplateResponse(\n            request=request, name=name, context=new_context\n        )\n\n    if func is None:\n        return partial(gt2fastapi)\n\n    @wraps(func)\n    async def async_wrapper(*args, **kwargs):\n        resp = await func(*args, **kwargs)\n        return _get_template_response(resp)\n\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        resp = func(*args, **kwargs)\n        return _get_template_response(resp)\n\n    return async_wrapper if inspect.iscoroutinefunction(func) else wrapper\n\n\n@app.get(\"/\", response_class=HTMLResponse)\n@gt2fastapi\ndef index(request: Request):\n    sza_pivot = (\n        get_sza()\n        .filter((pl.col(\"latitude\") == \"20\") \u0026 (pl.col(\"tst\") \u003c= \"1200\"))\n        .select(pl.col(\"*\").exclude(\"latitude\"))\n        .drop_nulls()\n        .pivot(values=\"sza\", index=\"month\", on=\"tst\", sort_columns=True)\n    )\n\n    sza_gt = (\n        GT(sza_pivot, rowname_col=\"month\")\n        .data_color(\n            domain=[90, 0],\n            palette=[\"rebeccapurple\", \"white\", \"orange\"],\n            na_color=\"white\",\n        )\n        .tab_header(\n            title=\"Solar Zenith Angles from 05:30 to 12:00\",\n            subtitle=html(\"Average monthly values at latitude of 20\u0026deg;N.\"),\n        )\n        .sub_missing(missing_text=\"\")\n    )\n\n    context = {\"sza_gt\": sza_gt}\n\n    return templates.TemplateResponse(\n        request=request, name=\"index.html\", context=context\n    )\n\n\n@app.get(\"/async\", response_class=HTMLResponse)\n@gt2fastapi\nasync def async_index(request: Request):\n    sza_pivot = (\n        get_sza()\n        .filter((pl.col(\"latitude\") == \"20\") \u0026 (pl.col(\"tst\") \u003c= \"1200\"))\n        .select(pl.col(\"*\").exclude(\"latitude\"))\n        .drop_nulls()\n        .pivot(values=\"sza\", index=\"month\", on=\"tst\", sort_columns=True)\n    )\n\n    sza_gt = (\n        GT(sza_pivot, rowname_col=\"month\")\n        .data_color(\n            domain=[90, 0],\n            palette=[\"orange\", \"white\", \"rebeccapurple\"],\n            na_color=\"white\",\n        )\n        .tab_header(\n            title=\"Solar Zenith Angles from 05:30 to 12:00\",\n            subtitle=html(\"Average monthly values at latitude of 20\u0026deg;N.\"),\n        )\n        .sub_missing(missing_text=\"\")\n    )\n\n    context = {\"sza_gt\": sza_gt}\n\n    return templates.TemplateResponse(\n        request=request, name=\"index.html\", context=context\n    )\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjrycw%2Fgt-fastapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjrycw%2Fgt-fastapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjrycw%2Fgt-fastapi/lists"}