FastAPI simplifies the process of rendering HTML templates and serving static files for building modern web applications. This guide explores FastAPI's integration with Jinja2 templates and static file configurations to create dynamic and efficient web projects.
fastapi itself does not provides built-in-support for rendering Html temapltes like traditional / web framework such as flask, django instead fastapi focuses on building APIs.
However you can use fastapi with template engine like jinja2 or any other template engine of your choice.
from fastapi import FastAPI,Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app=FastAPI()
template=Jinja2Templates(directory='templates')
@app.get("/",response_class=HTMLResponse)
async def index(request:Request):
return template.TemplateResponse("index.html",{"request":request,"title":"Let's Learn Fast API"})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to fastapi</title>
</head>
<body>
<h1>{{title}}</h1>
</body>
</html>
To serve StaticFiles, you can use StaticFiles class from fastapi.StaticFiles module. this allow you to serve css,js,images and other static files directory from the fast api application.
Organize your StaticFiles
first organize your static files (eg: css,js,images) with in directory in your project. By convention , you can name this directory as static
Configure staticfiles in fastapi
Create fastapi app and configure it to serve staticfiles using StaticFiles class.
app=FastAPI()
app.mount("/static",StaticFiles(directory='static'),name='static')<link rel="stylesheet" href="/static/css/style.css">Html Form template
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app=FastAPI()
app.mount("/static",StaticFiles(directory='static'),name='static')
template=Jinja2Templates(directory='templates')
@app.get("/contact",response_class=HTMLResponse)
async def contact(request:Request):
return template.TemplateResponse("contact.html",{"request":request})
@app.post("/contact")
async def contact_post(request:Request,email:str=Form(...),subject:str=Form(...),message:str=Form(...)):
print(email,subject,message)
return template.TemplateResponse("contact.html",{"request":request})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<form method="POST" action="/contact">
<h4 class="text-center text-dark">Contact Form</h4>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" required class="form-control" id="email" name='email'>
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="subject" class="form-label">Subject</label>
<input type="text" class="form-control" required id="subject" name='subject'>
</div>
<div class="form-floating">
<textarea class="form-control" name="message" required id="floatingTextarea"></textarea>
<label for="floatingTextarea">Message</label>
</div>
<button type="submit" class="btn btn-dark mt-5">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>
</html>cookies parameters
To handle cookies parameters in fastapi, you can use the cookies parameter type. This allows you to access and use cookies set by the client in Http request.
from fastapi import FastAPI,Request,Response,Cookie
app=FastAPI()
@app.get("/set-cookies")
async def set_cookies(response:Response):
response.set_cookie(key='cookie_key',value='cookie_values')
return {"message":"cookies set successfully"}
@app.get("/get-cookies")
async def set_cookies(request:Request):
cookie_value=request.cookies.get('cookie_key')
return {"cookie_value":cookie_value}
