<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pierre Maris on Medium]]></title>
        <description><![CDATA[Stories by Pierre Maris on Medium]]></description>
        <link>https://medium.com/@pierremaris?source=rss-32b76fa465d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xcd16KXyIGPEp_XGt3TWqA.png</url>
            <title>Stories by Pierre Maris on Medium</title>
            <link>https://medium.com/@pierremaris?source=rss-32b76fa465d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:04:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pierremaris/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WordPress sans PHP : Créez un site réactif avec FastAPI et HTMX]]></title>
            <link>https://medium.com/@pierremaris/wordpress-sans-php-cr%C3%A9ez-un-site-ultra-r%C3%A9actif-avec-fastapi-et-htmx-7145cfe9f2fe?source=rss-32b76fa465d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7145cfe9f2fe</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Pierre Maris]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 18:10:55 GMT</pubDate>
            <atom:updated>2026-01-20T23:07:42.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>WordPress sans PHP : Créez un site réactif avec FastAPI et HTMX</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AuNOisItt_qtOzYw7UvwA.png" /></figure><p>Je dois intégrer des fonctionnalités métier un peu complexes dans un site WordPress et je suis mauvais en PHP… Et je n’ai pas trop envie de progresser. Par contre, j’adore Python et FastAPI. En plus, une partie de l’application est déjà codée sur cet environnement. Et c’est avec cette stack que je suis le plus productif.</p><p>Il faut donc que je trouve une façon propre d’intégrer l’appli FastAPI tout en continuant deprofiter au mieux de l’environnement WordPress : gestion de contenus bien sûr, gestion des utilisateurs, des rôles et des permissions…</p><p>L’IHM de la partie métier est relativement simple mais je veux quand même quelque chose de dynamique… pour ne pas dire réactif. Mais j’ai encore moins envie de faire du React ou de l’Angular que du PHP! Et comme je crois beaucoup en l’approche de <a href="https://htmx.org/">htmx.org</a>, je vais l’utiliser pour intégrer le contenu de mon application dans les pages WordPress.</p><p>Je vais vous montrer les mécanismes de base de l’intégration jusqu’à finir par un exemple très simple de ToDo List intégrée dans une page WordPress.</p><h4>htmx.org</h4><p>Si vous ne connaissez pas la librairie htmx, tout est là :</p><blockquote>htmx extends and generalizes the core idea of HTML as a hypertext, opening up many more possibilities directly within the language:<br> — Now any element, not just anchors and forms, can issue an HTTP request<br> — Now any event, not just clicks or form submissions, can trigger requests<br> — Now any <a href="https://en.wikipedia.org/wiki/HTTP_Verbs">HTTP verb</a>, not just <em>GET</em> and <em>POST</em>, can be used<br>— Now any element, not just the entire window, can be the target for update by the request</blockquote><p>htmx permet de faire des appels AJAX et de gérer les événements sans écrire de code.</p><pre>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;!-- have a button POST a click via AJAX --&gt;<br>  &lt;button hx-post=&quot;/clicked&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>    Click Me<br>  &lt;/button&gt;</pre><p>Les attributs<a href="https://htmx.org/attributes/hx-post/">hx-post</a> et <a href="https://htmx.org/attributes/hx-swap/">hx-swap</a> du bouton disent à htmx:</p><blockquote>Quand un utilisateur clique le bouton, envoie une requête à /clicked et remplace le bouton entier par la réponse HTML retournée.</blockquote><p>C’est très simple mais très puissant.</p><p>Un autre exemple :</p><pre>&lt;div hx-get=&quot;/content&quot; hx-trigger=&quot;every 2s&quot; hx-swap=&quot;innerHTML&quot;&gt;<br>&lt;/div&gt;</pre><p>Toutes les 2 secondes, le contenu retourné par /content est placé à l’intérieur du &lt;div&gt;.</p><p>Et bien sûr, le contenu HTML retourné peut lui même contenir des balises htmx ce qui permet de développer une interaction complète avec l’utilisateur à l’intérieur d’un simple &lt;div&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHdZh9MrH4RjGbia4_56aQ.png" /><figcaption>Intégration WordPress/FastAPI with htmx</figcaption></figure><h4>htmx dans WordPress</h4><p>L’objectif est de pouvoir placer un bloc htmx dans un contenu WordPress</p><pre>&lt;div hx-get=&quot;/path-de-mon-appli&quot; hx-trigger=&quot;load&quot; hx-swap=&quot;innerHTML&quot;&gt;&lt;/div&gt;</pre><p>Pour faire ça, on peut utiliser un shortcode WordPress :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XC-YebPwkm2y-cgNMsEvQ.png" /><figcaption>Editeur de page WordPress</figcaption></figure><p>Si <a href="http://localhost:8080/hello">http://localhost:8080/hello</a> retourne “&lt;h2&gt;Hello from &lt;i&gt; Mon Application&lt;/i&gt;&lt;/h2&gt;”, on obtiendra :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4c8ymsRDq913knIWi2WVw.png" /><figcaption>Rendu du shortcode</figcaption></figure><p>Nous pouvons déclarer notre shortcode dans un plugin. Un plugin est un simple fichier php déposé dans le dossier wp-content/plugins de WordPress.</p><pre>&lt;?php<br>/**<br> * Plugin Name: HTMX Intégration<br> * Description: Demo of HTMX integration using shortcode<br> */<br>if (!defined(&#39;ABSPATH&#39;)) {<br>    exit; // Sécurité : empêcher l&#39;accès direct<br>}<br>add_shortcode(&#39;htmx_get&#39;, &#39;htmx_get_shortcode&#39;);<br>function htmx_get_shortcode($atts)<br>{<br>    wp_enqueue_script(<br>        &#39;htmx&#39;,<br>        &#39;https://unpkg.com/htmx.org@2.0.2&#39;,<br>        array(),<br>        false,<br>        true<br>    );<br>    wp_add_inline_script(&#39;htmx&#39;, &#39;htmx.config.selfRequestsOnly = false;&#39;);<br>    ob_start();<br>    ?&gt;<br>    &lt;div hx-get=&quot;&lt;?php echo $atts[&#39;url&#39;]; ?&gt;&quot; hx-trigger=&quot;load&quot; hx-swap=&quot;innerHTML&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;?php<br>    return ob_get_clean();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wUp-yty1cX111byqb7BsQ.png" /></figure><p>N’oubliez pas d’activer le plugin dans l’interface d’administration de WordPress.</p><p><strong>Explication du code :</strong><br><em>wp_enqueue_script()</em> va générer le code<br>&lt;script src=”https://unpkg.com/htmx.org@2.0.2?ver=6.9&quot; id=”htmx-js”&gt;&lt;/script&gt; dans la page qui contient le shortcode.</p><p>De la même manière <em>wp_add_inline_script(‘htmx’, ‘htmx.config.selfRequestsOnly = false;’)</em> va ajouter un script dans la page. Il s’agit de configurer htmx pour qu’il accepte de générer des requêtes vers des sites externes. C’est indispensable dans l’état de notre application car l’application métier (http://localhost:8000) n’est pas dans le même “domaine” que WordPress (http://localhost:8080). Dans l’architecture finale, ce paramètre ne sera plus utile puisque un proxy Nginx exposera WordPress et l’application sur une même adresse.</p><p>Ensuite <em>&lt;div hx-get=”&lt;?php echo $atts[‘url’]; ?&gt;” hx-trigger=”load” hx-swap=”innerHTML”&gt;<br> &lt;/div&gt; </em>génère le code html avec l’appel htmx vers l’url passée en paramètre du shortcode : <em>[htmx_get url=”http://localhost:8000/hello&quot;].</em></p><p>Voilà ! On a un shortcode qui permet d’intégrer le contenu d’une application externe dans notre page.</p><h4>FastAPI et authentification</h4><p>Maintenant, pour allons travailler sur l’application métier FastAPI et en particulier sur un mécanisme d’authentification/identification permettant de sécuriser les appels et d’identifier l’utilisateur connecté.</p><p>Pour authentifier les utilisateurs, lors d’une requête htmx vers l’application métier, nous demandons à WordPress de générer un “nonce” associé à l’utilisateur courant. Le nonce et l’ID de l’utilisateur sont envoyés à l’application avec la requête dans des header “X-WP-Nonce” et “X-WP-User-ID”.<br>A la réception de la requête, l’application demande à WordPress de confirmer la validité du couple nonce/userId. Si c’est ok, WordPress retourne les informations sur l’utilisateur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ECqbkkSEYRfbgf6Ms0Mkw.png" /></figure><p>Côté PHP, nous ajoutons le code de gestion du nonce au plugin :</p><pre>/**<br> * Generates a stateless nonce for authentication.<br> * Used for server-to-server verification where session tokens are not available.<br> */<br>function htmx_create_stateless_nonce($action, $user_id = null)<br>{<br>    if (!$user_id) {<br>        $user_id = get_current_user_id();<br>    }<br>    if (!$user_id) {<br>        return false;<br>    }</pre><pre>    $i = wp_nonce_tick();</pre><pre>    // Hash without session token<br>    return substr(wp_hash($i . &#39;|&#39; . $action . &#39;|&#39; . $user_id, &#39;nonce&#39;), -12, 10);<br>}</pre><pre>/**<br> * Verifies a stateless nonce.<br> */<br>function htmx_verify_stateless_nonce($nonce, $action, $user_id)<br>{<br>    if (empty($nonce) || empty($user_id)) {<br>        return false;<br>    }</pre><pre>    $i = wp_nonce_tick();</pre><pre>    // Check current tick<br>    $expected = substr(wp_hash($i . &#39;|&#39; . $action . &#39;|&#39; . $user_id, &#39;nonce&#39;), -12, 10);<br>    if (hash_equals($expected, $nonce)) {<br>        return 1;<br>    }</pre><pre>    // Check previous tick (12h window)<br>    $expected = substr(wp_hash(($i - 1) . &#39;|&#39; . $action . &#39;|&#39; . $user_id, &#39;nonce&#39;), -12, 10);<br>    if (hash_equals($expected, $nonce)) {<br>        return 2;<br>    }</pre><pre>    return false;<br>}</pre><pre>/**<br> * Endpoint to verify nonce.<br> */<br>function htmx_rest_verify_nonce($request)<br>{<br>    $params = $request-&gt;get_json_params();<br>    $nonce = isset($params[&#39;nonce&#39;]) ? $params[&#39;nonce&#39;] : &#39;&#39;;<br>    $user_id = isset($params[&#39;user_id&#39;]) ? intval($params[&#39;user_id&#39;]) : 0;<br>    $action = &#39;htmx_rest&#39;;</pre><pre>    if (!$user_id || !$nonce) {<br>        return new WP_Error(&#39;missing_params&#39;, &#39;Nonce or User ID missing&#39;, array(&#39;status&#39; =&gt; 400));<br>    }</pre><pre>    // Verify stateless nonce<br>    if (!htmx_verify_stateless_nonce($nonce, $action, $user_id)) {<br>        return new WP_Error(&#39;invalid_nonce&#39;, &#39;Invalid Nonce&#39; . $nonce, array(&#39;status&#39; =&gt; 401));<br>    }</pre><pre>    $user = get_userdata($user_id);<br>    if (!$user) {<br>        return new WP_Error(&#39;user_not_found&#39;, &#39;User not found&#39;, array(&#39;status&#39; =&gt; 404));<br>    }</pre><pre>    // Return User Context<br>    return array(<br>        &#39;id&#39; =&gt; $user-&gt;ID,<br>        &#39;user_login&#39; =&gt; $user-&gt;user_login,<br>        &#39;display_name&#39; =&gt; $user-&gt;display_name,<br>        &#39;roles&#39; =&gt; $user-&gt;roles,<br>        &#39;allcaps&#39; =&gt; $user-&gt;allcaps,<br>        &#39;is_admin&#39; =&gt; user_can($user, &#39;manage_options&#39;)<br>    );<br>}</pre><pre>add_action(&#39;rest_api_init&#39;, function () {<br>    register_rest_route(&#39;htmx/v1&#39;, &#39;/verify-nonce&#39;, array(<br>        &#39;methods&#39; =&gt; &#39;POST&#39;,<br>        &#39;callback&#39; =&gt; &#39;htmx_rest_verify_nonce&#39;,<br>        &#39;permission_callback&#39; =&gt; &#39;__return_true&#39;, // Validation inside<br>    ));<br>});</pre><p><em>wp_nonce_tick()</em> : Retourne un entier basé sur le temps (timestamp / 43200 secondes). C’est ce qui fait que le nonce expire après environ 24h (2 ticks).</p><p><em>wp_hash() </em>: Utilise les sels (salts) définis dans wp-config.php (NONCE_KEY et NONCE_SALT) pour créer une signature cryptographique inviolable sans ces clés.</p><p>L’authentification est sécurisé car seul votre site WordPress (qui possède les clés secrètes) peut générer un hash valide pour un user_id donné. Un attaquant ne peut pas inventer un nonce valide pour l’utilisateur.</p><p>Coté FastAPI, on a <em>authent.py</em> qui récupère les informations sur l’utilisateur en se basant sur les headers X-WP-Nonce et X-WP-User-ID:</p><pre>import httpx<br>from fastapi import Request, HTTPException<br>from typing import Optional, List, Dict<br>from pydantic import BaseModel, Field<br>import os<br>import time</pre><pre>class WPUser(BaseModel):<br>    id: int<br>    user_login: str<br>    display_name: str<br>    roles: List[str]<br>    capabilities: Dict[str, bool] = Field(alias=&quot;allcaps&quot;)<br>    is_admin: bool</pre><pre># Simple in-memory cache: { &quot;nonce:user_id&quot;: (WPUser, timestamp) }<br>_auth_cache: Dict[str, tuple[WPUser, float]] = {}<br>CACHE_TTL = 300  # 5 minutes</pre><pre>async def get_current_wp_user(request: Request) -&gt; Optional[WPUser]:<br>    &quot;&quot;&quot;<br>    Dependency that inspects headers, verifies nonce with WP, and returns the User.<br>    Uses an internal cache to avoid spamming WP API.<br>    &quot;&quot;&quot;<br>    nonce = request.headers.get(&quot;X-WP-Nonce&quot;)<br>    user_id_str = request.headers.get(&quot;X-WP-User-ID&quot;)</pre><pre>    if not nonce or not user_id_str:<br>        if request.method == &quot;OPTIONS&quot;:<br>            return None  # Skip auth for preflight</pre><pre>        if os.getenv(&quot;WP_NO_AUTH&quot;, &quot;0&quot;) == &quot;1&quot;:<br>            return WPUser(<br>                id=1,<br>                user_login=&quot;dev&quot;,<br>                display_name=&quot;Dev&quot;,<br>                roles=[&quot;administrator&quot;],<br>                allcaps={&quot;manage_options&quot;: True, &quot;manage_peq&quot;: True},<br>                is_admin=True,<br>            )</pre><pre>        raise HTTPException(status_code=401, detail=&quot;Missing WP Authentication Headers&quot;)</pre><pre>    try:<br>        user_id = int(user_id_str)<br>    except ValueError:<br>        raise HTTPException(status_code=401, detail=&quot;Invalid WP User ID&quot;)</pre><pre>    cache_key = f&quot;{nonce}:{user_id}&quot;<br>    if cache_key in _auth_cache:<br>        user, timestamp = _auth_cache[cache_key]<br>        if time.time() - timestamp &lt; CACHE_TTL:<br>            return user<br>        else:<br>            del _auth_cache[cache_key]  # Expired</pre><pre>    # Verify with WP<br>    wp_base = os.getenv(&quot;WP_API_BASE&quot;, &quot;http://localhost:8080/wp-json&quot;)<br>    verify_url = f&quot;{wp_base}/htmx/v1/verify-nonce&quot;</pre><pre>    async with httpx.AsyncClient() as client:<br>        try:<br>            resp = await client.post(<br>                verify_url, json={&quot;nonce&quot;: nonce, &quot;user_id&quot;: user_id}, timeout=5.0<br>            )<br>            if resp.status_code != 200:<br>                print(f&quot;WP Auth Failed: {resp.status_code} - {resp.text}&quot;)<br>                raise HTTPException(<br>                    status_code=401, detail=&quot;WP Nonce Verification Failed&quot;<br>                )</pre><pre>            data = resp.json()<br>            user = WPUser(**data)</pre><pre>            _auth_cache[cache_key] = (user, time.time())</pre><pre>            request.state.user = user<br>            return user</pre><pre>        except httpx.RequestError as e:<br>            print(f&quot;WP Auth Connection Error: {e}&quot;)<br>            raise HTTPException(<br>                status_code=503, detail=&quot;Authentication Service Unavailable&quot;<br>            )</pre><p>On utilise l’injection de dépendance de FastAPI pour injecter l’utilisateur dans les méthodes à sécuriser :</p><pre>@app.get(&quot;/hello&quot;)<br>def say_hello_to_user(<br>    request: Request, current_user: WPUser = Depends(get_current_wp_user)<br>):<br>   return HTMLResponse(f&quot;&lt;h2&gt;Hello &lt;b&gt;{{current_user.display_name}}&lt;/b&gt; from &lt;i&gt;{{APPLICATION_NAMEe}}&lt;/i&gt;&lt;/h2&gt;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIZjKipcXTStbAFyUuByVQ.png" /></figure><p>Si l’authentification échoue, <em>get_current_wp_user() </em>lève une exception 401 retournée à l’appelant.</p><p>Les composants de base de l’intégration sont en place!</p><h4>Example d’application : ToDo List</h4><p>Dans FastAPI, nous développons une API REST JSON standard qui permet de gérer une liste de tâches avec les méthodes GET pour récupérer toutes les tâches, POST pour créer une tâche et DELETE/{id} pour supprimer une tâche.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKt2kK4JeUWBltBG6Vq23g.png" /></figure><p><em>tasks.py</em></p><pre>from typing import List, Any<br>from pydantic import BaseModel<br>from fastapi import APIRouter, Depends, HTTPException, Request, Response<br>from fastapi.templating import Jinja2Templates<br>from authent import WPUser, get_current_wp_user<br>import uuid</pre><pre>router = APIRouter(<br>    prefix=&quot;/tasks&quot;,<br>    tags=[&quot;tasks&quot;],<br>)</pre><pre>templates = Jinja2Templates(directory=&quot;templates&quot;)</pre><pre>class TaskCreate(BaseModel):<br>    title: str</pre><pre>class Task(TaskCreate):<br>    id: str<br>    user_name: str</pre><pre>tasks: List[Task] = []</pre><pre>@router.get(&quot;/&quot;)<br>def get_tasks(<br>    request: Request, current_user: WPUser = Depends(get_current_wp_user)<br>) -&gt; List[Task]:<br>    if request.headers.get(&quot;hx-request&quot;) == &quot;true&quot;:<br>        return templates.TemplateResponse(<br>            &quot;tasks.html&quot;,<br>            {&quot;request&quot;: request, &quot;tasks&quot;: tasks},<br>        )<br>    return tasks<br></pre><pre>@router.post(&quot;/&quot;, response_model=Task)<br>def create_task(<br>    request: Request,<br>    task: TaskCreate,<br>    current_user: WPUser = Depends(get_current_wp_user),<br>) -&gt; Any:<br>    if not task.title:<br>        raise HTTPException(status_code=400, detail=&quot;Title is required&quot;)</pre><pre>    new_task = Task(<br>        id=str(uuid.uuid4()),<br>        title=task.title,<br>        user_name=current_user.display_name,<br>    )<br>    tasks.append(new_task)</pre><pre>    if request.headers.get(&quot;hx-request&quot;) == &quot;true&quot;:<br>        return templates.TemplateResponse(<br>            &quot;task_item.html&quot;,<br>            {&quot;request&quot;: request, &quot;task&quot;: new_task},<br>        )<br>    return new_task</pre><pre>@router.delete(&quot;/{task_id}&quot;)<br>def delete_task(<br>    task_id: str,<br>    request: Request,<br>    current_user: WPUser = Depends(get_current_wp_user),<br>) -&gt; Any:<br>    for task in tasks:<br>        if task.id == task_id:<br>            tasks.remove(task)<br>            if request.headers.get(&quot;hx-request&quot;) == &quot;true&quot;:<br>                return Response(status_code=200)<br>            return task<br>    raise HTTPException(status_code=404, detail=&quot;Task not found&quot;)</pre><p>Dans tous les appels, htmx ajoute un header <em>hx-request=true</em>. Si nous détectons ce header, l’API va retourner le fragment HTML à afficher dans la page WordPress plutôt que du JSON.</p><p>Le rendu HTML est fait par des templates Jinja2. Un GET sur /tasks affiche la liste des tâches précédée d’une zone de saisie à l’aide du template <em>tasks.html</em>.<br>Une saisie dans la zone déclenche un POST sur /tasks et le résultat est ajouté à la fin de la liste en utilisant le template <em>task_item.html.</em></p><p><em>templates/tasks.html</em></p><pre>&lt;form hx-post=&quot;http://localhost:8000/tasks/&quot; hx-target=&quot;#task-list&quot; hx-swap=&quot;beforeend&quot; hx-ext=&quot;json-enc&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;title&quot; placeholder=&quot;New task title&quot; required&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Add Task&lt;/button&gt;<br>&lt;/form&gt;</pre><pre>&lt;ul id=&quot;task-list&quot;&gt;<br>    {% for task in tasks %}<br>        {% include &quot;task_item.html&quot; %}<br>    {% endfor %}<br>&lt;/ul&gt;</pre><p><em>templates/task_item.html</em></p><pre>&lt;li id=&quot;task-{{ task.id }}&quot;&gt;<br>    {{ task.title }} ({{ task.user_name }})<br>    &lt;button hx-delete=&quot;http://localhost:8000/tasks/{{ task.id }}&quot; hx-target=&quot;#task-{{ task.id }}&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>        X<br>    &lt;/button&gt;<br>&lt;/li&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lu-HENImbYE81wVJzgRRuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IskvsmH6NL0F2jvzCVs5w.png" /></figure><p><strong>Remarque</strong> : pour conserver la compatibilité avec l’API JSON on demande à htmx d’envoyer les données en JSON plutôt qu’au format form, en utilisant l’extension <em>hx-ext=”json-enc”</em>. Pour utiliser cette extension, il faut charger le javascript correspondant dans le shortcode</p><pre>wp_enqueue_script(<br>        &#39;json-enc&#39;,<br>        &#39;https://unpkg.com/htmx.org@2.0.2/dist/ext/json-enc.js&#39;,<br>        array(&#39;htmx&#39;),<br>        false,<br>        true<br>    );</pre><h4>Conclusion</h4><p>Cet article présente uniquement les principes de base de l’intégration. En pratique, avec peu de choses en plus, l’architecture présentée a permis une intégration simple et rapide de l’application.</p><p><a href="https://medium.com/@pierremaris/integrate-fastapi-application-in-wordpress-with-htmx-109e863243a9">English version</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7145cfe9f2fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing PHP : Build Dynamic WordPress Apps with FastAPI & HTMX]]></title>
            <link>https://medium.com/@pierremaris/integrate-fastapi-application-in-wordpress-with-htmx-109e863243a9?source=rss-32b76fa465d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/109e863243a9</guid>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Pierre Maris]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 11:32:19 GMT</pubDate>
            <atom:updated>2026-01-20T21:51:26.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Writing PHP : Build Dynamic WordPress Apps with FastAPI &amp; HTMX</h3><figure><img alt="A screen with python logo on the left and the wordpress one on the righr" src="https://cdn-images-1.medium.com/max/1024/1*3AuNOisItt_qtOzYw7UvwA.png" /></figure><p>I need to integrate some fairly complex business features into a WordPress site, and I’m not very good at PHP… and I’m not really motivated to improve. On the other hand, I love Python and FastAPI. Besides, part of the application is already coded in that environment, and it’s the stack in which I’m the most productive.</p><p>So I need to find a clean way to integrate the FastAPI app while continuing to take full advantage of the WordPress environment: content management of course, as well as user management, roles, and permissions.</p><p>The UI for the business part is relatively simple, but I still want something dynamic — not to say reactive. But I’m even less interested in doing React or Angular than in doing PHP! And since I strongly believe in the htmx.org approach, I’m going to use it to integrate my application’s content into WordPress pages.</p><p>I’ll show you the basic integration mechanisms, ending with a very simple example of a ToDo list integrated into a WordPress page.</p><h4>htmx.org</h4><p>If you’re not familiar with the htmx library, everything is explained here:</p><p>htmx extends and generalizes the core idea of HTML as a hypertext, opening up many more possibilities directly within the language:</p><blockquote>- Now any element, not just anchors and forms, can issue an HTTP request</blockquote><blockquote>- Now any event, not just clicks or form submissions, can trigger requests</blockquote><blockquote>- Now any HTTP verb, not just GET and POST, can be used</blockquote><blockquote>- Now any element, not just the entire window, can be the target for updates triggered by a request</blockquote><p>htmx makes it possible to perform AJAX calls and handle events without writing any JavaScript code.</p><pre>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;!-- have a button POST a click via AJAX --&gt;<br>  &lt;button hx-post=&quot;/clicked&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>    Click Me<br>  &lt;/button&gt;</pre><p>The <a href="https://htmx.org/attributes/hx-post/">hx-post</a> and <a href="https://htmx.org/attributes/hx-swap/">hx-swap</a> attributes on this button tell htmx:</p><blockquote><em>“When a user clicks on this button, issue an AJAX request to /clicked, and replace the entire button with the HTML response.</em></blockquote><p>It’s very simple, yet very powerful.</p><p>Another example:</p><pre>&lt;div hx-get=&quot;/content&quot; hx-trigger=&quot;every 2s&quot; hx-swap=&quot;innerHTML&quot;&gt;<br>&lt;/div&gt;</pre><p>Every 2 seconds, the content returned by /content is inserted into the &lt;div&gt;.</p><p>And of course, the returned HTML content can itself contain htmx attributes, which makes it possible to build a fully interactive user experience inside a simple &lt;div&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I9jKEBS-riEEvb5C.png" /><figcaption>WordPress/FastAPI integration thru htmx</figcaption></figure><h4>htmx dans WordPress</h4><p>The goal is to be able to place an htmx block inside WordPress content.</p><pre>&lt;div hx-get=&quot;/path-de-mon-appli&quot; hx-trigger=&quot;load&quot; hx-swap=&quot;innerHTML&quot;&gt;&lt;/div&gt;</pre><p>To do this, we can use a WordPress shortcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7X4CRaheCichHv8.png" /></figure><p>WordPress page editor</p><p>If <a href="http://localhost:8080/hello"><em>http://localhost:8080/hello</em></a> returns “<em>&lt;h2&gt;Hello from &lt;i&gt;My Application&lt;/i&gt;&lt;/h2&gt;</em>”, we will get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7dtRimSvQ_24tkSV.png" /><figcaption>Shortcode output</figcaption></figure><p>We can declare our shortcode in a plugin. A plugin is simply a PHP file placed in WordPress’s wp-content/plugins directory.</p><p>For example:</p><pre>&lt;?php<br>/**<br> * Plugin Name: HTMX Intégration<br> * Description: Demo of HTMX integration using shortcode<br> */<br>if (!defined(&#39;ABSPATH&#39;)) {<br>    exit; // Sécurité : empêcher l&#39;accès direct<br>}<br>add_shortcode(&#39;htmx_get&#39;, &#39;htmx_get_shortcode&#39;);<br>function htmx_get_shortcode($atts)<br>{<br>    wp_enqueue_script(<br>        &#39;htmx&#39;,<br>        &#39;https://unpkg.com/htmx.org@2.0.2&#39;,<br>        array(),<br>        false,<br>        true<br>    );<br>    wp_add_inline_script(&#39;htmx&#39;, &#39;htmx.config.selfRequestsOnly = false;&#39;);<br>    ob_start();<br>    ?&gt;<br>    &lt;div hx-get=&quot;&lt;?php echo $atts[&#39;url&#39;]; ?&gt;&quot; hx-trigger=&quot;load&quot; hx-swap=&quot;innerHTML&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;?php<br>    return ob_get_clean();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yFofxLz4_U_Z0TvY.png" /></figure><p>Don’t forget to activate the plugin in the WordPress administration interface.</p><p><strong>Code explanation: </strong>wp_enqueue_script() will generate the following code in the page that contains the shortcode:<br><em>&lt;script src=”https://unpkg.com/htmx.org@2.0.2?ver=6.9&quot; id=”htmx-js”&gt;&lt;/script&gt;</em></p><p>Similarly, <em>wp_add_inline_script(‘htmx’, ‘htmx.config.selfRequestsOnly = false;’) </em>will add an inline script to the page. This configures htmx to allow requests to external sites. This is required in the current state of our application because the business application (<em>http://localhost:8000</em>) is not on the same “domain” as WordPress (<em>http://localhost:8080</em>). In the final architecture, this setting will no longer be necessary, since an Nginx proxy will expose WordPress and the application under the same address.</p><p>Then, <em>&lt;div hx-get=”&lt;?php echo $atts[‘url’]; ?&gt;” hx-trigger=”load” hx-swap=”innerHTML”&gt;&lt;/div&gt; </em>generates the HTML code with the htmx call to the URL passed as a parameter to the shortcode: <em>[htmx_get url=”http://localhost:8000/hello&quot;]</em>.</p><p><strong>That’s it! We now have a shortcode that allows us to embed the content of an external application into our page.</strong></p><h4><strong>FastAPI and authentication</strong></h4><p>Now we’re going to work on the FastAPI business application, and in particular on an authentication/identification mechanism to secure requests and identify the logged-in user.</p><p>To authenticate users, when an htmx request is sent to the business application, we ask WordPress to generate a “nonce” associated with the current user. The nonce and the user’s ID are sent to the application along with the request in the <em>X-WP-Nonce</em> and <em>X-WP-User-ID </em>headers.</p><p>When the request is received, the application asks WordPress to confirm that the nonce/userId pair is valid. If everything is OK, WordPress returns the user information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AuzSItQDei_i_Ege.png" /></figure><p>On the PHP side, we add the nonce handling code to the plugin:</p><pre>/**<br> * Generates a stateless nonce for authentication.<br> * Used for server-to-server verification where session tokens are not available.<br> */<br>function htmx_create_stateless_nonce($action, $user_id = null)<br>{<br>    if (!$user_id) {<br>        $user_id = get_current_user_id();<br>    }<br>    if (!$user_id) {<br>        return false;<br>    }<br>    $i = wp_nonce_tick();<br>    // Hash without session token<br>    return substr(wp_hash($i . &#39;|&#39; . $action . &#39;|&#39; . $user_id, &#39;nonce&#39;), -12, 10);<br>}<br>/**<br> * Verifies a stateless nonce.<br> */<br>function htmx_verify_stateless_nonce($nonce, $action, $user_id)<br>{<br>    if (empty($nonce) || empty($user_id)) {<br>        return false;<br>    }<br>    $i = wp_nonce_tick();<br>    // Check current tick<br>    $expected = substr(wp_hash($i . &#39;|&#39; . $action . &#39;|&#39; . $user_id, &#39;nonce&#39;), -12, 10);<br>    if (hash_equals($expected, $nonce)) {<br>        return 1;<br>    }<br>    // Check previous tick (12h window)<br>    $expected = substr(wp_hash(($i - 1) . &#39;|&#39; . $action . &#39;|&#39; . $user_id, &#39;nonce&#39;), -12, 10);<br>    if (hash_equals($expected, $nonce)) {<br>        return 2;<br>    }<br>    return false;<br>}<br>/**<br> * Endpoint to verify nonce.<br> */<br>function htmx_rest_verify_nonce($request)<br>{<br>    $params = $request-&gt;get_json_params();<br>    $nonce = isset($params[&#39;nonce&#39;]) ? $params[&#39;nonce&#39;] : &#39;&#39;;<br>    $user_id = isset($params[&#39;user_id&#39;]) ? intval($params[&#39;user_id&#39;]) : 0;<br>    $action = &#39;htmx_rest&#39;;<br>    if (!$user_id || !$nonce) {<br>        return new WP_Error(&#39;missing_params&#39;, &#39;Nonce or User ID missing&#39;, array(&#39;status&#39; =&gt; 400));<br>    }<br>    // Verify stateless nonce<br>    if (!htmx_verify_stateless_nonce($nonce, $action, $user_id)) {<br>        return new WP_Error(&#39;invalid_nonce&#39;, &#39;Invalid Nonce&#39; . $nonce, array(&#39;status&#39; =&gt; 401));<br>    }<br>    $user = get_userdata($user_id);<br>    if (!$user) {<br>        return new WP_Error(&#39;user_not_found&#39;, &#39;User not found&#39;, array(&#39;status&#39; =&gt; 404));<br>    }<br>    // Return User Context<br>    return array(<br>        &#39;id&#39; =&gt; $user-&gt;ID,<br>        &#39;user_login&#39; =&gt; $user-&gt;user_login,<br>        &#39;display_name&#39; =&gt; $user-&gt;display_name,<br>        &#39;roles&#39; =&gt; $user-&gt;roles,<br>        &#39;allcaps&#39; =&gt; $user-&gt;allcaps,<br>        &#39;is_admin&#39; =&gt; user_can($user, &#39;manage_options&#39;)<br>    );<br>}<br>add_action(&#39;rest_api_init&#39;, function () {<br>    register_rest_route(&#39;htmx/v1&#39;, &#39;/verify-nonce&#39;, array(<br>        &#39;methods&#39; =&gt; &#39;POST&#39;,<br>        &#39;callback&#39; =&gt; &#39;htmx_rest_verify_nonce&#39;,<br>        &#39;permission_callback&#39; =&gt; &#39;__return_true&#39;, // Validation inside<br>    ));<br>});</pre><p><em>wp_nonce_tick()</em>: Returns an integer based on time (timestamp / 43200 seconds). This is what makes the nonce expire after about 24 hours (2 ticks).</p><p><em>wp_hash()</em>: Uses the salts defined in wp-config.php (NONCE_KEY and NONCE_SALT) to create a cryptographic signature that can’t be forged without those keys.</p><p>Authentication is secure because only your WordPress site (which owns the secret keys) can generate a valid hash for a given user_id. An attacker can’t just make up a valid nonce for the user.</p><p>On the FastAPI side, we have authent.py, which retrieves user information based on the X-WP-Nonce and X-WP-User-ID headers:</p><pre>import httpx<br>from fastapi import Request, HTTPException<br>from typing import Optional, List, Dict<br>from pydantic import BaseModel, Field<br>import os<br>import time<br><br>class WPUser(BaseModel):<br>    id: int<br>    user_login: str<br>    display_name: str<br>    roles: List[str]<br>    capabilities: Dict[str, bool] = Field(alias=&quot;allcaps&quot;)<br>    is_admin: bool<br><br># Simple in-memory cache: { &quot;nonce:user_id&quot;: (WPUser, timestamp) }<br>_auth_cache: Dict[str, tuple[WPUser, float]] = {}<br>CACHE_TTL = 300  # 5 minutes<br><br>async def get_current_wp_user(request: Request) -&gt; Optional[WPUser]:<br>    &quot;&quot;&quot;<br>    Dependency that inspects headers, verifies nonce with WP, and returns the User.<br>    Uses an internal cache to avoid spamming WP API.<br>    &quot;&quot;&quot;<br>    nonce = request.headers.get(&quot;X-WP-Nonce&quot;)<br>    user_id_str = request.headers.get(&quot;X-WP-User-ID&quot;)<br>    if not nonce or not user_id_str:<br>        if request.method == &quot;OPTIONS&quot;:<br>            return None  # Skip auth for preflight<br>        if os.getenv(&quot;WP_NO_AUTH&quot;, &quot;0&quot;) == &quot;1&quot;:<br>            return WPUser(<br>                id=1,<br>                user_login=&quot;dev&quot;,<br>                display_name=&quot;Dev&quot;,<br>                roles=[&quot;administrator&quot;],<br>                allcaps={&quot;manage_options&quot;: True, &quot;manage_peq&quot;: True},<br>                is_admin=True,<br>            )<br>        raise HTTPException(status_code=401, detail=&quot;Missing WP Authentication Headers&quot;)<br>    try:<br>        user_id = int(user_id_str)<br>    except ValueError:<br>        raise HTTPException(status_code=401, detail=&quot;Invalid WP User ID&quot;)<br>    cache_key = f&quot;{nonce}:{user_id}&quot;<br>    if cache_key in _auth_cache:<br>        user, timestamp = _auth_cache[cache_key]<br>        if time.time() - timestamp &lt; CACHE_TTL:<br>            return user<br>        else:<br>            del _auth_cache[cache_key]  # Expired<br>    # Verify with WP<br>    wp_base = os.getenv(&quot;WP_API_BASE&quot;, &quot;http://localhost:8080/wp-json&quot;)<br>    verify_url = f&quot;{wp_base}/htmx/v1/verify-nonce&quot;<br>    async with httpx.AsyncClient() as client:<br>        try:<br>            resp = await client.post(<br>                verify_url, json={&quot;nonce&quot;: nonce, &quot;user_id&quot;: user_id}, timeout=5.0<br>            )<br>            if resp.status_code != 200:<br>                print(f&quot;WP Auth Failed: {resp.status_code} - {resp.text}&quot;)<br>                raise HTTPException(<br>                    status_code=401, detail=&quot;WP Nonce Verification Failed&quot;<br>                )<br>            data = resp.json()<br>            user = WPUser(**data)<br>            _auth_cache[cache_key] = (user, time.time())<br>            request.state.user = user<br>            return user<br>        except httpx.RequestError as e:<br>            print(f&quot;WP Auth Connection Error: {e}&quot;)<br>            raise HTTPException(<br>                status_code=503, detail=&quot;Authentication Service Unavailable&quot;<br>            )</pre><p>We use FastAPI’s dependency injection to inject the user into the methods that need to be secured:</p><pre>@app.get(&quot;/hello&quot;)<br>def say_hello_to_user(<br>    request: Request, current_user: WPUser = Depends(get_current_wp_user)<br>):<br>   return HTMLResponse(f&quot;&lt;h2&gt;Hello &lt;b&gt;{{current_user.display_name}}&lt;/b&gt; from &lt;i&gt;{{APPLICATION_NAMEe}}&lt;/i&gt;&lt;/h2&gt;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*44fqbjvfZGk6pWeL.png" /></figure><p>If authentication fails, <em>get_current_wp_user()</em> raises a 401 exception that is returned to the caller.</p><p><strong>The basic building blocks of the integration are now in place!</strong></p><h3><strong>Example application: ToDo List</strong></h3><p>In FastAPI, we build a standard JSON REST API that allows managing a task list, with:</p><ul><li>GET to retrieve all tasks,</li><li>POST to create a task, and</li><li>DELETE /{id} to delete a task.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rBnQoSVIuQ6HTqDG.png" /></figure><p><em>tasks.py</em></p><pre>from typing import List, Any<br>from pydantic import BaseModel<br>from fastapi import APIRouter, Depends, HTTPException, Request, Response<br>from fastapi.templating import Jinja2Templates<br>from authent import WPUser, get_current_wp_user<br>import uuid<br>router = APIRouter(<br>    prefix=&quot;/tasks&quot;,<br>    tags=[&quot;tasks&quot;],<br>)<br>templates = Jinja2Templates(directory=&quot;templates&quot;)<br>class TaskCreate(BaseModel):<br>    title: str<br>class Task(TaskCreate):<br>    id: str<br>    user_name: str<br>tasks: List[Task] = []<br>@router.get(&quot;/&quot;)<br>def get_tasks(<br>    request: Request, current_user: WPUser = Depends(get_current_wp_user)<br>) -&gt; List[Task]:<br>    if request.headers.get(&quot;hx-request&quot;) == &quot;true&quot;:<br>        return templates.TemplateResponse(<br>            &quot;tasks.html&quot;,<br>            {&quot;request&quot;: request, &quot;tasks&quot;: tasks},<br>        )<br>    return tasks<br><br>@router.post(&quot;/&quot;, response_model=Task)<br>def create_task(<br>    request: Request,<br>    task: TaskCreate,<br>    current_user: WPUser = Depends(get_current_wp_user),<br>) -&gt; Any:<br>    if not task.title:<br>        raise HTTPException(status_code=400, detail=&quot;Title is required&quot;)<br>    new_task = Task(<br>        id=str(uuid.uuid4()),<br>        title=task.title,<br>        user_name=current_user.display_name,<br>    )<br>    tasks.append(new_task)<br>    if request.headers.get(&quot;hx-request&quot;) == &quot;true&quot;:<br>        return templates.TemplateResponse(<br>            &quot;task_item.html&quot;,<br>            {&quot;request&quot;: request, &quot;task&quot;: new_task},<br>        )<br>    return new_task<br>@router.delete(&quot;/{task_id}&quot;)<br>def delete_task(<br>    task_id: str,<br>    request: Request,<br>    current_user: WPUser = Depends(get_current_wp_user),<br>) -&gt; Any:<br>    for task in tasks:<br>        if task.id == task_id:<br>            tasks.remove(task)<br>            if request.headers.get(&quot;hx-request&quot;) == &quot;true&quot;:<br>                return Response(status_code=200)<br>            return task<br>    raise HTTPException(status_code=404, detail=&quot;Task not found&quot;)</pre><p>In all requests, htmx adds the header <em>hx-request=true</em>. If we detect this header, the API returns the HTML fragment to be displayed in the WordPress page instead of JSON.</p><p>The HTML rendering is handled by Jinja2 templates. A GET request to <em>/tasks</em> displays the task list preceded by an input area using the <em>tasks.html</em> template.</p><p>Entering text in the input field triggers a POST request to <em>/tasks</em>, and the result is appended to the end of the list using the <em>task_item.html</em> template.</p><p><em>templates/tasks.html</em></p><pre>&lt;form hx-post=&quot;http://localhost:8000/tasks/&quot; hx-target=&quot;#task-list&quot; hx-swap=&quot;beforeend&quot; hx-ext=&quot;json-enc&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;title&quot; placeholder=&quot;New task title&quot; required&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Add Task&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;ul id=&quot;task-list&quot;&gt;<br>    {% for task in tasks %}<br>        {% include &quot;task_item.html&quot; %}<br>    {% endfor %}<br>&lt;/ul&gt;</pre><p><em>templates/task_item.html</em></p><pre>&lt;li id=&quot;task-{{ task.id }}&quot;&gt;<br>    {{ task.title }} ({{ task.user_name }})<br>    &lt;button hx-delete=&quot;http://localhost:8000/tasks/{{ task.id }}&quot; hx-target=&quot;#task-{{ task.id }}&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>        X<br>    &lt;/button&gt;<br>&lt;/li&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ac5bA9diQDl5YUQY.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaLn1msQcf24m7AK.png" /></figure><p><strong>Note:</strong> To preserve compatibility with the JSON API, we ask htmx to send data in JSON rather than in form format, using the extension <em>hx-ext=”json-enc”</em>. To use this extension, the corresponding JavaScript must be loaded in the shortcode.</p><pre>wp_enqueue_script(<br>        &#39;json-enc&#39;,<br>        &#39;https://unpkg.com/htmx.org@2.0.2/dist/ext/json-enc.js&#39;,<br>        array(&#39;htmx&#39;),<br>        false,<br>        true<br>    );</pre><h4><strong>Conclusion</strong></h4><p>This article only presents the basic principles of the integration. In practice, with just a little more work, the proposed architecture enabled a simple and fast integration of the application.</p><p><a href="https://medium.com/@pierremaris/wordpress-sans-php-cr%C3%A9ez-un-site-ultra-r%C3%A9actif-avec-fastapi-et-htmx-7145cfe9f2fe">French version</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=109e863243a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>