DEV Community

Free Python Code
Free Python Code

Posted on • Updated on

How to use Templates in FastAPI

Hi πŸ™‚πŸ–

Welcome to my new post, In this post, I will show you how to use HTML templates in FastAPI. FastAPI provides amazing methods to render templates in easy ways. You can use any template engine you want with FastAPI.
FastAPI supports Jinja2, the same one used by Flask and other tools.

step 1

Install jinja2
pip install jinja2

step 2

Create folders You need to create two folders.

1 - templates

Inside this folder, you will create the HTML files you want to display.

2 - static
This folder is used for static files like CSS and Javascript.

step 3

Inside templates folder create welcome.html page

<html>
<head>
    <title>Welcome</title>
    <link href="{{ url_for('static', path='/css/style.css') }}" rel="stylesheet">
</head>
<body>
    <div class="user-name">
        <h1>Welcome : {{ name }} ;)</h1>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now we need to make another folder called css inside static folder to add style.css file πŸ€—

.user-name {
    margin: 100px auto;
    width: 60%;
    background-color: #673AB7;
    padding: 20px;
    color: white;
    text-align: center;
    font-family: monospace;
}
Enter fullscreen mode Exit fullscreen mode

step 4

Create the main.py file and import the required modules.

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
Enter fullscreen mode Exit fullscreen mode

Setting up static folders and template directories


app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory = 'templates')
Enter fullscreen mode Exit fullscreen mode

Create route called welcome this route will take name and display it into welcome.html page

@app.get('/welcome/{name}', response_class = HTMLResponse)
def welcome(name : str, request : Request):
    return templates.TemplateResponse(
        'welcome.html', 
        {'request': request, 'name': name}
    )
Enter fullscreen mode Exit fullscreen mode

Now we are ready to run the app. 😎

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

result

Image description

Now we're done πŸ€—

Don't forget to like and follow πŸ™‚

Support me on PayPal πŸ€—
https://www.paypal.com/paypalme/amr396

Top comments (0)