Templates¶
You can use any template engine you want withFastAPI.
A common choice is Jinja2, the same one used by Flask and other tools.
There are utilities to configure it easily that you can use directly in yourFastAPI application (provided by Starlette).
Install dependencies¶
Make sure you create avirtual environment, activate it, and installjinja2:
$pipinstalljinja2---> 100%UsingJinja2Templates¶
- Import
Jinja2Templates. - Create a
templatesobject that you can reuse later. - Declare a
Requestparameter in thepath operation that will return a template. - Use the
templatesyou created to render and return aTemplateResponse, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template.
fromfastapiimportFastAPI,Requestfromfastapi.responsesimportHTMLResponsefromfastapi.staticfilesimportStaticFilesfromfastapi.templatingimportJinja2Templatesapp=FastAPI()app.mount("/static",StaticFiles(directory="static"),name="static")templates=Jinja2Templates(directory="templates")@app.get("/items/{id}",response_class=HTMLResponse)asyncdefread_item(request:Request,id:str):returntemplates.TemplateResponse(request=request,name="item.html",context={"id":id})Note
Before FastAPI 0.108.0, Starlette 0.29.0, thename was the first parameter.
Also, before that, in previous versions, therequest object was passed as part of the key-value pairs in the context for Jinja2.
Tip
By declaringresponse_class=HTMLResponse the docs UI will be able to know that the response will be HTML.
Technical Details
You could also usefrom starlette.templating import Jinja2Templates.
FastAPI provides the samestarlette.templating asfastapi.templating just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same withRequest andStaticFiles.
Writing templates¶
Then you can write a template attemplates/item.html with, for example:
<html><head> <title>Item Details</title> <link href="{{url_for('static',path='/styles.css')}}" rel="stylesheet"></head><body> <h1><a href="{{url_for('read_item',id=id)}}">Item ID:{{id}}</a></h1></body></html>Template Context Values¶
In the HTML that contains:
Item ID:{{id}}...it will show theid taken from the "context"dict you passed:
{"id":id}For example, with an ID of42, this would render:
Item ID: 42Templateurl_for Arguments¶
You can also useurl_for() inside of the template, it takes as arguments the same arguments that would be used by yourpath operation function.
So, the section with:
<a href="{{url_for('read_item',id=id)}}">...will generate a link to the same URL that would be handled by thepath operation functionread_item(id=id).
For example, with an ID of42, this would render:
<ahref="/items/42">Templates and static files¶
You can also useurl_for() inside of the template, and use it, for example, with theStaticFiles you mounted with thename="static".
<html><head> <title>Item Details</title> <link href="{{url_for('static',path='/styles.css')}}" rel="stylesheet"></head><body> <h1><a href="{{url_for('read_item',id=id)}}">Item ID:{{id}}</a></h1></body></html>In this example, it would link to a CSS file atstatic/styles.css with:
h1{color:green;}And because you are usingStaticFiles, that CSS file would be served automatically by yourFastAPI application at the URL/static/styles.css.
More details¶
For more details, including how to test templates, checkStarlette's docs on templates.







