{"id":13780526,"url":"https://github.com/maces/fastapi-htmx","last_synced_at":"2025-05-13T12:56:48.877Z","repository":{"id":142768550,"uuid":"614085915","full_name":"maces/fastapi-htmx","owner":"maces","description":"Extension for FastAPI to make HTMX easier to use.","archived":false,"fork":false,"pushed_at":"2025-03-24T06:35:04.000Z","size":90,"stargazers_count":297,"open_issues_count":10,"forks_count":10,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-30T00:29:34.383Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"lgpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/maces.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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":"2023-03-14T21:31:27.000Z","updated_at":"2025-04-16T07:20:31.000Z","dependencies_parsed_at":"2024-01-15T23:27:27.048Z","dependency_job_id":"1541e89b-c9b0-43af-9b64-a398de452385","html_url":"https://github.com/maces/fastapi-htmx","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maces%2Ffastapi-htmx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maces%2Ffastapi-htmx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maces%2Ffastapi-htmx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maces%2Ffastapi-htmx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/maces","download_url":"https://codeload.github.com/maces/fastapi-htmx/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253948346,"owners_count":21988953,"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":[],"created_at":"2024-08-03T18:01:16.822Z","updated_at":"2025-05-13T12:56:48.852Z","avatar_url":"https://github.com/maces.png","language":"Python","readme":"# FastAPI-HTMX\n\nExtension for FastAPI to make HTMX easier to use.\n\nFastAPI-HTMX is an opinionated extension for FastAPI to speed up development of lightly interactive web applications. FastAPI-HTMX is implemented as a decorator, so it can be used on endpoints selectively. Furthermore it reduces boilerplate for Jinja2 template handling and allows for rapid prototyping by providing convenient helpers.\n\n[![Tests](https://github.com/maces/fastapi-htmx/actions/workflows/github-actions-tests.yml/badge.svg)](https://github.com/maces/fastapi-htmx/actions/workflows/github-actions-tests.yml)\n[![Version](https://img.shields.io/pypi/v/fastapi-htmx?logo=pypi\u0026logoColor=white\u0026color=2ab049)](https://pypi.org/project/fastapi-htmx/)\n[![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-htmx.svg?color=2ab049)](https://pypi.org/project/fastapi-htmx/)\n[![Experimental Support Chat](https://img.shields.io/badge/ChatGPT-Experimental_Support_Chat-white?logo=chatbot\u0026color=2ab049)](https://chat.openai.com/g/g-FdDQll0CW-fastapihtmx)\n\n\n## Install\n\ninstall via `pip`:\n```\n$ pip install fastapi-htmx\n```\n\ninstall via `poetry`:\n```\n$ poetry add fastapi-htmx\n```\n\n\n## Usage\n\n### Getting Started\n\nBasic example using FastAPI with `fastapi-htmx`\n\n`my_app/api.py`:\n```python\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import htmx, htmx_init\n\napp = FastAPI()\nhtmx_init(templates=Jinja2Templates(directory=Path(\"my_app\") / \"templates\"))\n\n@app.get(\"/\", response_class=HTMLResponse)\n@htmx(\"index\", \"index\")\nasync def root_page(request: Request):\n    return {\"greeting\": \"Hello World\"}\n\n@app.get(\"/customers\", response_class=HTMLResponse)\n@htmx(\"customers\")\nasync def get_customers(request: Request):\n    return {\"customers\": [\"John Doe\", \"Jane Doe\"]}\n```\n\nNote that:\n- `htmx()` got parameters, specifying the Jinja2 template to use\n- `htmx_init()` is needed for FastAPI-HTMX to find the templates\n- **There is no direct handling of the template needed, it only needs to be specified and the needed variables need to be returned**. This way endpoints can be designed in a familiar way to standard REST endpoints in FastAPI.\n    - This simplifies modularizing the app later (see below) and also providing a REST API if needed. See the \"Usage\" section for further examples.\n    - `get_customers` does not respond with the whole web page, but only with a part of it. See the [HTMX documentation](https://htmx.org/docs/#introduction) on how HTMX merges partials into the current web page.\n- **`request: Request` although not used in the endpoint directly, it is currently required for the decorator to work!**\n\nThe [Jinja2 templates](https://jinja.palletsprojects.com/en/3.1.x/templates/) to go along with the above code need to be placed like specified in `htmx_init` in `my_app/templates/` in order for the example to work.\n\nThe root page `my_app/templates/index.jinja2`:\n```jinja2\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eHello FastAPI-HTMX\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1\u003e{{ greeting }}\u003c/h1\u003e\n    \u003cbutton\n        hx-get=\"/customers\"\n        hx-swap=\"innerHTML\"\n        hx-target=\"#customers_list\"\n    \u003e\n        Load Data\n    \u003c/button\u003e\n    \u003cdiv id=\"customers_list\"\u003e\u003c/div\u003e\n    \u003cscript src=\"https://unpkg.com/htmx.org@1.9.6\"\u003e\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\nThe [partial template to load with HTMX](https://htmx.org/docs/#introduction) `my_app/templates/customers.jinja2`:\n```jinja2\n\u003cul\u003e\n    {% for customer in customers %}\n        \u003cli\u003e{{ customer }}\u003c/li\u003e\n    {% endfor %}\n\u003c/ul\u003e\n```\n\n\n### Main Concept\n\nThe decorator `htmx` provides the following helpers:\n\n- `partial_template_name` The partial template to use\n- `full_template_name` The full page template to use when URL rewriting + history is used\n- `*_template_constructor` For DRY code, in case the logic to gather all needed variables is needed multiple times\n\nSeeing these arguments one might ask themselves: Why all these parameters? The answer is an opinionated take on how to design modular endpoints wit partials and url-rewriting support:\n\nThe idea behind FastAPI-HTMX is to maintain a modular structure in the app and with the endpoints. Similar to a REST API with a [SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA). This way the frontend can be modular as well. This majorly helps with supporting [URL rewriting and the history](https://htmx.org/docs/#history) in the frontend:\n\n- A simple endpoint just answers with the partial.\n- Without it, if the URL is rewritten and a user navigates back, reloads the page or copies the URL and opens it in another tab or shares the URL, only the partial would be shown in the browser.\n\n**To enable SPA like functionality FastAPI-HTMX uses the concept of partials and fullpages as arguments for the decorator and requires to return a dict of the needed variables**. Note that returning anything else than a `Mapping` like a dict in the route, leads FastAPI-HTMX to return that instead of a template.\n\nIn order to support this SPA like functionality in an app, see the following example:\n\n`my_app/api_with_constructors.py`:\n```python\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import htmx, htmx_init\n\napp = FastAPI()\nhtmx_init(templates=Jinja2Templates(directory=Path(\"my_app\") / \"templates\"))\n\ndef construct_customers():\n    return {\"customers\": [\"John Doe\", \"Jane Doe\"]}\n\ndef construct_root_page():\n    return {\n        \"greeting\": \"Hello World\",\n        **construct_customers()\n    }\n\n@app.get(\"/\", response_class=HTMLResponse)\n@htmx(\"index\", \"index\")\nasync def root_page(request: Request):\n    return construct_root_page()\n\n@app.get(\"/customers\", response_class=HTMLResponse)\n@htmx(\"customers\", \"index\", construct_customers, construct_root_page)\nasync def get_customers(request: Request):\n    pass\n```\n\nNote that:\n- The `construct_*` functions are added, they now return the data\n    - **`construct_root_page` gathers all variables specified needed for the root page, including those for partials**\n        - **This also means you must avoid naming conflicts across endpoints, so dicts can be merged.**\n        - Costly operations can still be ignored, just use if statements in the template or similar\n- The decorators arguments are extended\n    - The second argument is the fullpage template which is used when the endpoint is called directly (new tab, navigation or reload)\n        - **E.g. since `construct_root_page` gathers all the data for the whole page, the whole page can be returned to the client**\n    - The other arguments are just to save some boilerplate code handling the [`HX-Request` header](https://htmx.org/attributes/hx-push-url/)\n        - **There is no need to use the arguments for the constructor functions, they are just for convenience.** If needed the endpoint can be used for the logic as well. Especially if no URL rewriting is needed.\n\nFor the above code to work the `my_app/templates/index.jinja2` needs to be changed as well. The changes are in the button and target div.\nChanged root page `my_app/templates/index.jinja2`:\n```jinja2\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eHello FastAPI-HTMX\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1\u003e{{ greeting }}\u003c/h1\u003e\n    \u003cbutton\n        hx-get=\"/customers\"\n        hx-push-url=\"true\"\n        hx-swap=\"innerHTML\"\n        hx-target=\"#customers_list\"\n    \u003e\n        Load Data\n    \u003c/button\u003e\n    \u003cdiv id=\"customers_list\"\u003e\n        {% include 'customers.jinja2' %}\n    \u003c/div\u003e\n    \u003cscript src=\"https://unpkg.com/htmx.org@1.9.6\"\u003e\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\nNote that:\n- `hx-push-url=\"true\"` was added to the button\n- The partial is now loaded by default requiring the main endpoint to also provide the needed variables like shown above\n\nThe unchanged partial `my_app/templates/customers.jinja2`:\n```jinja2\n\u003cul\u003e\n    {% for customer in customers %}\n        \u003cli\u003e{{ customer }}\u003c/li\u003e\n    {% endfor %}\n\u003c/ul\u003e\n```\n\nTo add additional partials and endpoints just repeat the same logic:\n- Include the partial in the parent Jinja2 template, like the main template. A hierarchy is possible as well.\n- Refactor the partials endpoints logic into a function\n    - Add it's return value to the parents constructor function like done above in `construct_root_page`\n    - Add the parents template and constructor function to the partials endpoints `htmx` decorator arguments\n\n\n### Advanced Usage\n\n\n#### Handling `HX-Request` manually\n\nIn case the `htmx()` arguments for partial and fullpage callables are not flexible enough, an endpoint can be used like usual. For a bit more convenience the `HX-Request` header is easily accessible via `request.hx_request`:\n\n`my_app/api_with_hx_request.py`:\n```python\nfrom pathlib import Path\n\nfrom fastapi import FastAPI\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import HXRequest, htmx, htmx_init\n\napp = FastAPI()\nhtmx_init(templates=Jinja2Templates(directory=Path(\"my_app\") / \"templates\"))\n\ndef my_partial(email_id: int = None):\n    return {\"email_id\": email_id}\n\ndef fullpage(email_id: int = None):\n    return {**my_partial(email_id)}\n\n@app.get(\"/email/{email_id}\", response_class=HTMLResponse)\n@htmx(\"email_detail\", \"index\")\ndef get_email(request: HXRequest, email_id: int):\n    if request.hx_request:\n        return my_partial(email_id)\n    else:\n        return fullpage(email_id)\n```\n\n`my_app/templates/index.jinja2`:\n```jinja2\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\u003chead\u003e\u003ctitle\u003eHello FastAPI-HTMX\u003c/title\u003e\u003c/head\u003e\n\u003cbody\u003e\n    \u003cdiv id=\"email_detail\"\u003e\n        {% include 'email_detail.jinja2' %}\n    \u003c/div\u003e\n    \u003cscript src=\"https://unpkg.com/htmx.org@1.9.6\"\u003e\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n`my_app/templates/email_detail.jinja2`:\n```jinja2\n\u003cp\u003e{{ email_id }}\u003c/p\u003e\n```\n\n\n#### Filters\n\nIn order to use [custom Jinja2 filters](https://jinja.palletsprojects.com/en/3.1.x/api/#custom-filters) like the following, configure them like below.\n\n`my_app/templates/customer.jinja2`:\n```Jinja2\n\u003cp\u003e{{ customer.created|datetime_format }}\u003c/p\u003e\n```\n\nAdd custom filters for use in Jinja2 templates:\n`my_app/api_template_filters.py`:\n```python\nfrom pathlib import Path\nfrom datetime import datetime\n\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import htmx_init\n\ndef datetime_format(value: datetime, format=\"%H:%M %d.%m.%Y\"):\n    return value.strftime(format) if value is not None else \"\"\n\ntemplates = Jinja2Templates(directory=Path(\"my_app\") / \"templates\")\ntemplates.env.filters[\"datetime_format\"] = datetime_format\nhtmx_init(templates=templates)\n# ...\n```\n\n\n#### Multiple Template Directories\n\nFor bigger apps, multiple template directories might be needed. For example if the app is split into several modules connected with routers. For this case template collections can be used. With `htmx_init()` multiple template collections can be defined. In each endpoint instead of the templates name (`account`) the collection gets specified as well, like this: `Tpl(SHOP, \"account\")`. This works for partials and full pages.\n\n`my_app/api_multiple_template_paths.py`:\n```python\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import htmx, htmx_init, TemplateSpec as Tpl\n\nSHOP = \"shop\"\nBACKEND = \"backend\"\n\napp = FastAPI()\ntemplates = {\n    SHOP: Jinja2Templates(directory=Path(\"my_app\") / SHOP / \"templates\"),\n    BACKEND: Jinja2Templates(directory=Path(\"my_app\") / BACKEND / \"templates\")\n}\nhtmx_init(templates=templates)\n\n@app.get(\"/account\", response_class=HTMLResponse)\n@htmx(Tpl(SHOP, \"account\"))\nasync def get_account(request: Request):\n    pass\n\n@app.get(\"/products\", response_class=HTMLResponse)\n@htmx(Tpl(BACKEND, \"products\"))\nasync def get_products(request: Request):\n    pass\n\n```\n\n`my_app/shop/templates/account.jinja2`:\n```jinja2\n\u003ch1\u003eMy Account\u003c/h1\u003e\n```\n\n`my_app/backend/templates/products.jinja2`:\n```jinja2\n\u003ch1\u003eProducts\u003c/h1\u003e\n```\n\n\n#### Other template file extensions for SOME endpoints\n\nIn case SOME endpoints templates got another file extension than the rest, it can be specified in the `@htmx()` decorator:\n\n`my_app/api_template_file_extension.py`:\n```python\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import htmx, htmx_init\n\napp = FastAPI()\nhtmx_init(templates=Jinja2Templates(directory=Path(\"my_app\") / \"templates\"))\n\n@app.get(\"/customers\", response_class=HTMLResponse)\n@htmx(\"customers\", template_extension=\"html\")\nasync def get_customers(request: Request):\n    pass\n# ...\n```\n\n`my_app/templates/customers.html`:\n```jinja2\n\u003ch1\u003eCustomer\u003c/h1\u003e\n```\n\n\n#### Other template file extensions for ALL endpoints\n\nIn case ALL endpoints templates got another file extension than the default `jinja2`, it can be overriden in `htmx_init()` like this:\n\n`my_app/api_template_file_extension.py`:\n```python\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_htmx import htmx, htmx_init\n\napp = FastAPI()\ntemplates = Jinja2Templates(directory=Path(\"my_app\") / \"templates\")\nhtmx_init(templates=templates, file_extension=\"html\")\n\n@app.get(\"/customers\", response_class=HTMLResponse)\n@htmx(\"customers\")\nasync def get_customers(request: Request):\n    pass\n```\n\n`my_app/templates/customers.html`:\n```jinja2\n\u003ch1\u003eCustomer\u003c/h1\u003e\n```\n","funding_links":[],"categories":["Third Party Packages 📦 \u003ca name = \"tools\"\u003e\u003c/a\u003e"],"sub_categories":["Helper Libraries"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaces%2Ffastapi-htmx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaces%2Ffastapi-htmx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaces%2Ffastapi-htmx/lists"}