FastAPI API

The FastAPI integration provides a Jinja2Blocks class that extends FastAPI’s built-in Jinja2Templates class to add support for rendering specific blocks from templates.

API Reference

FastAPI integration for jinja2-fragments.

This module provides FastAPI-compatible template rendering with support for rendering individual Jinja2 blocks. It’s built on top of the Starlette implementation since FastAPI uses Starlette under the hood.

For pure Starlette applications, you can use jinja2_fragments.starlette directly.

exception jinja2_fragments.fastapi.InvalidContextError[source]

Bases: Exception

class jinja2_fragments.fastapi.Jinja2Blocks(directory: str | PathLike[str] | Sequence[str | PathLike[str]], *, context_processors: list[Callable[[Request], dict[str, Any]]] | None = None, **env_options: Any)[source]
class jinja2_fragments.fastapi.Jinja2Blocks(*, env: Environment, context_processors: list[Callable[[Request], dict[str, Any]]] | None = None)

Bases: Jinja2Templates

TemplateResponse(*args, **kwargs)[source]

Generate an HTTP response with a rendered template.

This method renders a specified template with the given context and produces an HTTP response that includes the rendered content, as well as an appropriate status code.

Parameters:
  • template_name – The name of the template file to be rendered.

  • context – A dictionary of variables to be made available in the template.

  • status_code – The HTTP status code for the response. Defaults to 200 (OK).

Return type:

Response

Returns:

A Starlette-compatible HTTP Response object containing the rendered template.

Raises:
  • InvalidContextError – If the provided context is invalid or malformed.

  • TemplateNotFound – If the specified template cannot be located.