# How to pass dynamic data to a Gradio Blocks on each FastAPI request?

**URL:** <https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576>\
**Category:** Beginners\
**Created:** [April 9, 2025, 9:50am UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576 "2025-04-09T09:50:26Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tarun008](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/tarun008/32/45131_2.png) [@Tarun008](https://discuss.huggingface.co/u/Tarun008)\
**Post date:** [April 9, 2025, 9:50am UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/1 "2025-04-09T09:50:26Z")

</div>

I have a FASTAPI server that serves different requests and on call of /chatbot I want to render the Gradio block with some message that is passed dynamically to the app.

```auto
@app.get("/chatbot") 
def render_chatbot(request: Request):
    username = request.query_params.get('username', 'admin')
    gradio_blocks = GradioApp(username)
    return HTMLResponse(gradio_blocks)

```

I have implemented the GradioApp function, but how can I pass the variable based on request to GradioApp?

```auto
def GradioApp(username: str):
    with gr.Blocks(title="ChatBot", css=style_css) as demo:
    ...
    return demo

```

Any ideas are welcome. Thank you very much!

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](https://discuss.huggingface.co/u/John6666)\
**Post date:** [April 9, 2025, 11:10am UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/2 "2025-04-09T11:10:52Z")

</div>

Hmm… **auth\_dependency**?

> <https://github.com/gradio-app/gradio/issues/8755>
>
> \- \[x \] I have searched to see if a similar issue already exists.
> I found simila…r issues, but nobody ever asked for this feature. Nor did somebody asked precisely for this 
> 
> \*\*Is your feature request related to a problem? Please describe.\*\*  
> If I mount a gradio app on a fastapi app:
> \`\`\`
> app = gr.mount\_gradio\_app(
> app,
> chatbot\_gradio\_demo,
> path="/mega\_fancy\_ml\_route",
> auth\_dependency=get\_user,
> )
> 
> \# Dependency to get the current user
> def get\_user(request: Request):
> user = request.session.get("user")
> if user:
> return user\["name"\]
> return None
> \`\`\`
> 
> I can successfully show a 401 User not authenticated page.
> However this is somehow ugly, I really would like to redirect users to the login page.
> I tried with a middleware, but it requires complex overengineering to handle ssl/tls/certificates with redirects, and creates other big problems with different browsers, or corporate proxies.
> I also tried to make the get\_user function throw a custom exception, and create a fastapi exception\_handler to redirect the user to the login page, as showed in \[this stackoverflow answer\](https://stackoverflow.com/a/76887329) however, mount\_gradio\_app makes this route returns a response BEFORE the exception\_handler is triggered:
> \`\`\`
> class RequiresLogin(Exception):
> pass
> \# Dependency to get the current user
> def get\_user(request: Request):
> user = request.session.get("user")
> if user:
> return user\["name"\]
> raise RequiresLogin("You must be logged in to access this")
> @app.exception\_handler(RequiresLogin)
> async def requires\_login(request: Request, \_: Exception):
> return RedirectResponse("/")
> 
> app = gr.mount\_gradio\_app(
> app,
> chatbot\_gradio\_demo,
> path="/mega\_fancy\_ml\_route",
> auth\_dependency=get\_user,
> )
> \`\`\`
> 
> This causes the following runtime error
> \`RuntimeError: Caught handled exception, but response already started.\`
> 
> In other words I tried a lot of methods but I cannot find an elegant way, or at least a working one.
> 
> \*\*Describe the solution you'd like\*\*  
> What I really would love to have, is another parameter for the mount\_gradio\_app function, that allows a redirect (probably to the login page) when the user is not authenticated. Something like the following unauth\_redirect parameter:
> 
> \`\`\`
> app = gr.mount\_gradio\_app(
> app,
> chatbot\_gradio\_demo,
> path="/mega\_fancy\_ml\_route",
> auth\_dependency=get\_user,
> unauth\_redirect='/login'
> )
> 
> something similar to fastapi Depends() but with a redirect feature.
> \`\`\`
> 
> \*\*Additional context\*\*  
> Another solution could be to make all gradio app components invisible, and show a button or something that allow the users to login. But this requires also some overengineering.

> **[Sharing Your App](https://www.gradio.app/guides/sharing-your-app#o-auth-with-external-providers)**
>
> A Step-by-Step Gradio Tutorial

---

<div class="post-metadata">

**Author:** ![Tarun008](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/tarun008/32/45131_2.png) [@Tarun008](https://discuss.huggingface.co/u/Tarun008)\
**Post date:** [April 9, 2025, 1:07pm UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/3 "2025-04-09T13:07:01Z")

</div>

Lets take an example what I am trying to achieve.  
I am authenticate the users and getting call back to **/callback** endpoint with **username** and other details stored in **cookies**.

```auto
@router.get("/callback")
def callback(request: Request):
    response = RedirectResponse(url="/chatbot")
    username = request.cookies.get("username")

    return response

```

Which is redirecting the request to the **/chatbot** endpoint.  
I have mounted the **/chatbot** some like this for gradio blocks:

```auto
app = gr.mount_gradio_app(app, launch_chatbot(""), path="/chatbot")

```

I have **launch\_chatbot** function some like:

```auto
def launch_chatbot(username=""):
    logger.info(f"Access Token: {username}")
    with gr.Blocks(title="Naviga-ChatBot", css=style_css, head=f"<script src=\"{script_js}\"></script>") as demo:

    # UI implementation and other logic

    return demo

```

Now I am looking for a way to pass this username variable to this gradio UI.  
I have tried different ways but failed to achieve this.

As per my observation, I might be wrong this **gr.mount\_gradio\_app** loads the code at the start of the program it does not re-render the code when **/chatbot** is called.

Please let me know if I am missing something. Thanks.

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](https://discuss.huggingface.co/u/John6666)\
**Post date:** [April 9, 2025, 1:51pm UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/4 "2025-04-09T13:51:45Z")

</div>

It’s a bit rough, but how about embedding it in the response?

```python
@app.get("/callback")
async def callback(request: Request):
    response = RedirectResponse(url="/chatbot")
    username = request.cookies.get("username")
    response.url = f"{response.url}?username={username}"
    return response

```

```python
@app.get("/chatbot")
async def render_chatbot(request: Request):
    username = request.query_params.get('username', 'guest')
    
    with gr.Blocks() as demo:
        gr.Markdown(f"Welcome, {username}!")
        # Add other dynamic components based on the username
        
    return HTMLResponse(demo)

```

---

<div class="post-metadata">

**Author:** ![Tarun008](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/tarun008/32/45131_2.png) [@Tarun008](https://discuss.huggingface.co/u/Tarun008)\
**Post date:** [April 9, 2025, 2:45pm UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/5 "2025-04-09T14:45:32Z")

</div>

Thanks for the suggestion; however, if we go with this approach, there is no problem passing values to **/chatbot** , but **return HTMLResponse(demo)** doesn’t work.

As per my observation, we can not return gr.Block() using:

```auto
from fastapi.responses import HTMLResponse

```

It gives the below error:  
**AttributeError: ‘Blocks’ object has no attribute ‘encode’**

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](https://discuss.huggingface.co/u/John6666)\
**Post date:** [April 9, 2025, 2:58pm UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/6 "2025-04-09T14:58:12Z")

</div>

> <https://github.com/fastapi/fastapi/issues/3436>
>
> Hi,
> 
> I created an index.html file that displays "Moderation" with the \<p\> tag.…
> 
> In my main.py there is: 
> 
> from fastapi import FastAPI
> from fastapi.responses import HTMLResponse
> import os
> app = FastAPI ()
> @ app.get ("/ testHTML /", response\_class = HTMLResponse)
> async def read\_items ():
> f = open ("index.html", "r")
> return HTMLResponse (f.read ())
> 
> But when I test I see this on the webpage:  
> !\[image\](https://user-images.githubusercontent.com/71176675/123992083-95381080-d9cb-11eb-8b32-034f7d29eaff.png)
> I tried to add utf-8 meta tag to the HTML but it didn't change anything, I think it's an encoding problem in the HTMLResponse.

It seems that this can be avoided by encoding it in advance, but I was unable to find any examples of HTMLResponse. There were examples of Response.

---

<div class="post-metadata">

**Author:** ![untest](https://avatars.discourse-cdn.com/v4/letter/u/a9adbd/32.png) [@untest](https://discuss.huggingface.co/u/untest)\
**Post date:** [April 28, 2025, 6:05am UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/7 "2025-04-28T06:05:36Z")

</div>

@Tarun008 were you able to make it work finally ?

---

<div class="post-metadata">

**Author:** ![KateWinslet](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/katewinslet/32/26764_2.png) [@KateWinslet](https://discuss.huggingface.co/u/KateWinslet)\
**Post date:** [May 1, 2025, 12:26pm UTC](https://discuss.huggingface.co/t/how-to-pass-dynamic-data-to-a-gradio-blocks-on-each-fastapi-request/149576/8 "2025-05-01T12:26:47Z")

</div>

> [@Tarun008](#):
>
> I have a FASTAPI server that serves different requests and on call of /chatbot I want to render the Gradio block with some message that is passed [Holyland Gifts](https://holylandmerchandise.com/) dynamically to the app.
> 
> ```auto
> @app.get("/chatbot") 
> def render_chatbot(request: Request):
> username = request.query_params.get('username', 'admin')
> gradio_blocks = GradioApp(username)
> return HTMLResponse(gradio_blocks)
> 
> ```
> 
> I have implemented the GradioApp function, but how can I pass the variable based on request to GradioApp?
> 
> ```auto
> def GradioApp(username: str):
> with gr.Blocks(title="ChatBot", css=style_css) as demo:
> ...
> return demo
> 
> ```
> 
> Any ideas are welcome. Thank you very much!

You can pass the username to Gradio by setting it as a parameter in your Gradio app’s input component. For example, you could use gr.Textbox(value=username) within GradioApp. Modify your GradioApp function to accept and use the username dynamically in the interface.
