Search code examples
pythonjinja2fastapiuvicorn

Link files from html using fastapi and jinja2


Hi I'm trying to link to an json file from html code using fastapi and jinja2 but the link is not working. I guess i have to tell fastapi how to find the file or something like that.. I get an json (api) answer instad of the file..

{"detail":"Not Found"}

The python code:

from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory='templates')


@app.get('/data', response_class=HTMLResponse)
async def data(request: Request):
    return templates.TemplateResponse('data.html', {
        'request': request
    })

And the HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
        <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
        <title>Data</title>
    </head>
    <body>
        <div class="ui container">
            <h1>
                Data downloader:
            </h1>
            <a href="../json/data.json" target="_blank">
                Data
            </a>
        </div>

    </body>
</html>

Solution

  • This code did it..

    python:

    from fastapi import FastAPI, Form, Request
    from fastapi.responses import HTMLResponse
    from fastapi.templating import Jinja2Templates
    from fastapi.staticfiles import StaticFiles
    app = FastAPI()
    app.mount("/json", StaticFiles(directory="json"), name="json")
    
    templates = Jinja2Templates(directory='templates')
    
    
    @app.get('/data', response_class=HTMLResponse)
    async def data(request: Request):
        return templates.TemplateResponse('data.html', {
            'request': request
        })
    

    HTML:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
            <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
            <title>Data</title>
        </head>
        <body>
            <div class="ui container">
                <h1>
                    Data downloader:
                </h1>
                <a href="{{ url_for('json', path='/data.json') }}" target="_blank">
                    Data
                </a>
            </div>
    
        </body>
    </html>
    

    So it was the import and use of StaticFiles that first code dint have