poli-page-fastapi 0.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ """FastAPI integration for the Poli Page PDF rendering SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from poli_page_fastapi._version import __version__
6
+ from poli_page_fastapi.dependencies import PoliPageDependency, get_poli_page_client
7
+ from poli_page_fastapi.exceptions import poli_page_exception_handler
8
+ from poli_page_fastapi.lifespan import poli_page_lifespan
9
+ from poli_page_fastapi.responses import (
10
+ DocumentRedirectResponse,
11
+ PdfResponse,
12
+ PdfStreamResponse,
13
+ PreviewResponse,
14
+ )
15
+ from poli_page_fastapi.settings import PoliPageSettings
16
+ from poli_page_fastapi.setup import setup_poli_page
17
+
18
+ __all__ = [
19
+ "DocumentRedirectResponse",
20
+ "PdfResponse",
21
+ "PdfStreamResponse",
22
+ "PoliPageDependency",
23
+ "PoliPageSettings",
24
+ "PreviewResponse",
25
+ "__version__",
26
+ "get_poli_page_client",
27
+ "poli_page_exception_handler",
28
+ "poli_page_lifespan",
29
+ "setup_poli_page",
30
+ ]
@@ -0,0 +1,40 @@
1
+ """Internal: RFC 6266 / RFC 8187 (ex-5987) Content-Disposition encoding.
2
+
3
+ Same contract as the other Poli Page framework integrations (django-poli-page's
4
+ ``_build_disposition`` is the reference): control characters are stripped, ``\\``
5
+ and ``"`` are escaped as quoted-pairs, and non-ASCII filenames get the dual
6
+ ``filename="<ascii-fallback>"; filename*=UTF-8''<percent-encoded>`` notation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from urllib.parse import quote
13
+
14
+ # C0 controls (incl. TAB, CR, LF), DEL and C1 controls. None of them belong in a
15
+ # filename, and CR/LF would split the header (response splitting).
16
+ _CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
17
+
18
+
19
+ def build_content_disposition(filename: str, *, inline: bool = False) -> str:
20
+ """Return a Content-Disposition header value with correct filename encoding.
21
+
22
+ ASCII filenames: ``attachment; filename="..."``.
23
+ Non-ASCII filenames: dual form —
24
+ ``attachment; filename="<ascii-fallback>"; filename*=UTF-8''<percent-encoded>``.
25
+ """
26
+ disposition = "inline" if inline else "attachment"
27
+ clean = _CONTROL_CHARS.sub("", filename)
28
+ if clean.isascii():
29
+ return f'{disposition}; filename="{_quoted_string_content(clean)}"'
30
+ ascii_fallback = clean.encode("ascii", "replace").decode("ascii")
31
+ encoded = quote(clean, safe="")
32
+ return (
33
+ f'{disposition}; filename="{_quoted_string_content(ascii_fallback)}"; '
34
+ f"filename*=UTF-8''{encoded}"
35
+ )
36
+
37
+
38
+ def _quoted_string_content(value: str) -> str:
39
+ """Escape ``\\`` and ``"`` as quoted-pairs (RFC 9110 §5.6.4)."""
40
+ return value.replace("\\", "\\\\").replace('"', '\\"')
@@ -0,0 +1 @@
1
+ __version__ = "0.13.0"
@@ -0,0 +1,67 @@
1
+ """FastAPI dependency factory and class for the Poli Page SDK client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+ from typing import Any
7
+
8
+ from poli_page import PoliPage
9
+
10
+ from poli_page_fastapi.settings import PoliPageSettings
11
+
12
+
13
+ def _settings_to_kwargs(settings: PoliPageSettings) -> dict[str, Any]:
14
+ kwargs: dict[str, Any] = {}
15
+ if settings.api_key is not None:
16
+ kwargs["api_key"] = settings.api_key
17
+ if settings.base_url is not None:
18
+ kwargs["base_url"] = settings.base_url
19
+ if settings.timeout is not None:
20
+ kwargs["timeout"] = settings.timeout
21
+ if settings.max_retries is not None:
22
+ kwargs["max_retries"] = settings.max_retries
23
+ if settings.retry_delay is not None:
24
+ kwargs["retry_delay"] = settings.retry_delay
25
+ return kwargs
26
+
27
+
28
+ @lru_cache(maxsize=1)
29
+ def get_poli_page_client() -> PoliPage:
30
+ """Return the process-wide memoised PoliPage client.
31
+
32
+ Used as `Depends(get_poli_page_client)` in route signatures. The lru_cache
33
+ decorator guarantees one instance per process; to inject a mock in tests,
34
+ use `app.dependency_overrides[get_poli_page_client] = lambda: mock`.
35
+ """
36
+ settings = PoliPageSettings()
37
+ return PoliPage(**_settings_to_kwargs(settings))
38
+
39
+
40
+ class PoliPageDependency:
41
+ """Callable dependency that builds a per-instance client.
42
+
43
+ Use when you want explicit settings or a per-router client distinct
44
+ from the global memo. Each instance memoises its own client.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ *,
50
+ settings: PoliPageSettings | None = None,
51
+ client: PoliPage | None = None,
52
+ ) -> None:
53
+ self._settings = settings
54
+ self._cached_client: PoliPage | None = client
55
+
56
+ def __call__(self) -> PoliPage:
57
+ if self._cached_client is not None:
58
+ return self._cached_client
59
+ settings = self._settings or PoliPageSettings()
60
+ self._cached_client = PoliPage(**_settings_to_kwargs(settings))
61
+ return self._cached_client
62
+
63
+ def close(self) -> None:
64
+ """Close the underlying SDK client and clear the cache."""
65
+ if self._cached_client is not None:
66
+ self._cached_client.close()
67
+ self._cached_client = None
@@ -0,0 +1,37 @@
1
+ """Exception handler answering a `PoliPageError` as JSON.
2
+
3
+ `setup_poli_page(app)` registers it by default. To register it yourself:
4
+
5
+ from poli_page import PoliPageError
6
+ from poli_page_fastapi import poli_page_exception_handler
7
+
8
+ app.add_exception_handler(PoliPageError, poli_page_exception_handler)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from fastapi import Request
14
+ from fastapi.responses import JSONResponse
15
+ from poli_page import PoliPageError
16
+
17
+
18
+ def poli_page_exception_handler(request: Request, exc: Exception) -> JSONResponse:
19
+ """Answer a `PoliPageError` with its `to_payload()` body.
20
+
21
+ Body: exactly `exc.to_payload()`, `{code, message, status, requestId}` (camelCase
22
+ on the wire, `null` when unknown). Status: the payload's `status` (the API status,
23
+ 503 for `network_error`, 504 for `timeout`, 502 for `invalid_response`), or 500 when
24
+ it is `null` (`io_error`, `invalid_options`, a `DOWNLOAD_FAILED` with no storage
25
+ status).
26
+
27
+ Any other exception is re-raised, so the application's own handling applies.
28
+ """
29
+ if not isinstance(exc, PoliPageError):
30
+ raise exc
31
+ payload = exc.to_payload()
32
+ status = payload["status"]
33
+ return JSONResponse(
34
+ status_code=status if isinstance(status, int) else 500,
35
+ content=payload,
36
+ headers={"Cache-Control": "no-store, private"},
37
+ )
@@ -0,0 +1,27 @@
1
+ """ASGI lifespan helper: warm the client at startup, close at shutdown."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ from contextlib import asynccontextmanager
7
+
8
+ from fastapi import FastAPI
9
+
10
+ from poli_page_fastapi.dependencies import get_poli_page_client
11
+
12
+
13
+ @asynccontextmanager
14
+ async def poli_page_lifespan(app: FastAPI) -> AsyncIterator[None]:
15
+ """ASGI lifespan that warms the Poli Page client on startup and closes
16
+ it on shutdown.
17
+
18
+ Usage:
19
+
20
+ app = FastAPI(lifespan=poli_page_lifespan)
21
+ """
22
+ client = get_poli_page_client()
23
+ try:
24
+ yield
25
+ finally:
26
+ client.close()
27
+ get_poli_page_client.cache_clear()
File without changes
@@ -0,0 +1,192 @@
1
+ """Response helpers — Starlette response subclasses with the right headers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Iterator
6
+ from contextlib import AbstractContextManager
7
+
8
+ import anyio
9
+ import anyio.to_thread
10
+ from starlette.background import BackgroundTask
11
+ from starlette.responses import Response, StreamingResponse
12
+ from starlette.types import Receive, Scope, Send
13
+
14
+ from poli_page_fastapi._headers import build_content_disposition
15
+
16
+ _PDF_DEFAULT_HEADERS = {
17
+ "Cache-Control": "no-store, private",
18
+ "X-Content-Type-Options": "nosniff",
19
+ }
20
+
21
+
22
+ class PdfResponse(Response):
23
+ """A PDF response with correct Content-Type, Content-Disposition, Cache-Control."""
24
+
25
+ media_type = "application/pdf"
26
+
27
+ def __init__(
28
+ self,
29
+ content: bytes,
30
+ *,
31
+ status_code: int = 200,
32
+ filename: str = "document.pdf",
33
+ inline: bool = False,
34
+ background: BackgroundTask | None = None,
35
+ headers: dict[str, str] | None = None,
36
+ ) -> None:
37
+ # Why: status_code is also exposed so FastAPI's OpenAPI generator can
38
+ # discover the default response status when this class is used as
39
+ # `response_class=PdfResponse` (otherwise /openapi.json returns 500
40
+ # — UnboundLocalError in fastapi/openapi/utils.py).
41
+ merged: dict[str, str] = dict(headers or {})
42
+ merged["Content-Disposition"] = build_content_disposition(filename, inline=inline)
43
+ for k, v in _PDF_DEFAULT_HEADERS.items():
44
+ merged.setdefault(k, v)
45
+ super().__init__(
46
+ content=content,
47
+ status_code=status_code,
48
+ media_type="application/pdf",
49
+ headers=merged,
50
+ background=background,
51
+ )
52
+
53
+
54
+ class _OpenedStream:
55
+ """The chunks of an SDK stream entered at once; exhausting them, or an error, exits it."""
56
+
57
+ def __init__(self, stream: AbstractContextManager[Iterator[bytes]]) -> None:
58
+ self._stream = stream
59
+ self._chunks = iter(stream.__enter__())
60
+ self._open = True
61
+
62
+ def __iter__(self) -> Iterator[bytes]:
63
+ return self
64
+
65
+ def __next__(self) -> bytes:
66
+ try:
67
+ return next(self._chunks)
68
+ except BaseException:
69
+ self.close()
70
+ raise
71
+
72
+ def close(self) -> None:
73
+ if self._open:
74
+ self._open = False
75
+ self._stream.__exit__(None, None, None)
76
+
77
+
78
+ class PdfStreamResponse(StreamingResponse):
79
+ """A streamed PDF response.
80
+
81
+ Pass the SDK's stream as is: `PdfStreamResponse(client.render.pdf_stream(input))`.
82
+ The render and the download start here, in the route, so a `PoliPageError` raises
83
+ before the response starts and reaches the error handler. The stream is closed when
84
+ the response ends: read to the end, failed, or the client disconnected, and before a
85
+ `background` task runs. A response built and never sent leaves it to the garbage
86
+ collector.
87
+
88
+ Opening the stream does the render and the download's first request synchronously:
89
+ build the response in a `def` route (FastAPI runs it in its threadpool), or in
90
+ `run_in_threadpool` from an `async def` route.
91
+
92
+ An iterator of bytes (sync or async) is streamed as given: an error it raises comes
93
+ after the 200 has been sent.
94
+ """
95
+
96
+ media_type = "application/pdf"
97
+
98
+ def __init__(
99
+ self,
100
+ content: AbstractContextManager[Iterator[bytes]] | Iterator[bytes] | AsyncIterator[bytes],
101
+ *,
102
+ status_code: int = 200,
103
+ filename: str = "document.pdf",
104
+ inline: bool = False,
105
+ background: BackgroundTask | None = None,
106
+ headers: dict[str, str] | None = None,
107
+ ) -> None:
108
+ merged: dict[str, str] = dict(headers or {})
109
+ merged["Content-Disposition"] = build_content_disposition(filename, inline=inline)
110
+ for k, v in _PDF_DEFAULT_HEADERS.items():
111
+ merged.setdefault(k, v)
112
+ self._opened: _OpenedStream | None = None
113
+ if isinstance(content, AbstractContextManager):
114
+ content = self._opened = _OpenedStream(content)
115
+ super().__init__(
116
+ content=content,
117
+ status_code=status_code,
118
+ media_type="application/pdf",
119
+ headers=merged,
120
+ background=background,
121
+ )
122
+
123
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
124
+ if self._opened is None:
125
+ await super().__call__(scope, receive, send)
126
+ return
127
+ # Why: Starlette runs the background task inside __call__, after the body. Run
128
+ # it here instead, once the SDK stream is closed, so the stream's connection
129
+ # does not stay open for as long as the task runs.
130
+ background = self.background
131
+ self.background = None
132
+ try:
133
+ await super().__call__(scope, receive, send)
134
+ finally:
135
+ self.background = background
136
+ # Starlette never closes a sync iterator: on a client disconnect it cancels
137
+ # the send (ASGI < 2.4) or raises ClientDisconnect (2.4+). Close the SDK
138
+ # stream here, shielded from that cancellation, so its connection returns.
139
+ with anyio.CancelScope(shield=True):
140
+ await anyio.to_thread.run_sync(self._opened.close)
141
+ # Starlette's own rule: the task runs when the response returns, a disconnect
142
+ # message included, and not when it raises (ClientDisconnect on ASGI 2.4+).
143
+ if background is not None:
144
+ await background()
145
+
146
+
147
+ class PreviewResponse(Response):
148
+ """An HTML preview response — text/html; charset=utf-8."""
149
+
150
+ media_type = "text/html; charset=utf-8"
151
+
152
+ def __init__(
153
+ self,
154
+ content: str,
155
+ *,
156
+ status_code: int = 200,
157
+ background: BackgroundTask | None = None,
158
+ headers: dict[str, str] | None = None,
159
+ ) -> None:
160
+ merged: dict[str, str] = dict(headers or {})
161
+ merged.setdefault("Cache-Control", "no-store, private")
162
+ merged.setdefault("X-Content-Type-Options", "nosniff")
163
+ super().__init__(
164
+ content=content,
165
+ status_code=status_code,
166
+ media_type="text/html; charset=utf-8",
167
+ headers=merged,
168
+ background=background,
169
+ )
170
+
171
+
172
+ class DocumentRedirectResponse(Response):
173
+ """A 302 (or 308 if permanent=True) redirect to a document's presigned URL."""
174
+
175
+ def __init__(
176
+ self,
177
+ url: str,
178
+ *,
179
+ permanent: bool = False,
180
+ background: BackgroundTask | None = None,
181
+ headers: dict[str, str] | None = None,
182
+ ) -> None:
183
+ merged: dict[str, str] = dict(headers or {})
184
+ merged["Location"] = url
185
+ merged.setdefault("Cache-Control", "no-store, private")
186
+ status_code = 308 if permanent else 302
187
+ super().__init__(
188
+ content=b"",
189
+ status_code=status_code,
190
+ headers=merged,
191
+ background=background,
192
+ )
@@ -0,0 +1,90 @@
1
+ """Pydantic-settings reader for POLI_PAGE_* env vars."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+
9
+ from pydantic import Field, field_validator, model_validator
10
+ from pydantic_settings import BaseSettings, SettingsConfigDict
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # pp_{environment}_{32 lowercase hex}, the SDK contract's full-key format. It only
15
+ # drives a startup warning: the API is the authority on keys, so a mismatch never
16
+ # stops the client.
17
+ _API_KEY_RE = re.compile(r"pp_(?=[a-z][a-z0-9-]{0,19}_)[a-z][a-z0-9]*(?:-[a-z0-9]+)*_[0-9a-f]{32}")
18
+
19
+
20
+ def _warn_if_malformed(key: str) -> None:
21
+ if not _API_KEY_RE.fullmatch(key):
22
+ # No part of the key reaches the log: even a pp_{environment}_ prefix can
23
+ # be a pasted secret fragment.
24
+ logger.warning(
25
+ "POLI_PAGE_API_KEY does not match the key format "
26
+ "pp_{environment}_{32 lowercase hex characters}; starting anyway, "
27
+ "the Poli Page API decides whether the key is valid."
28
+ )
29
+
30
+
31
+ class PoliPageSettings(BaseSettings):
32
+ """Pydantic-settings reader for POLI_PAGE_* env vars.
33
+
34
+ Maps one-to-one with the SDK's PoliPage(__init__) kwargs. Unset values
35
+ are left as None so the SDK applies its own defaults — we never duplicate
36
+ default literals between SDK and integration.
37
+ """
38
+
39
+ model_config = SettingsConfigDict(
40
+ env_prefix="POLI_PAGE_",
41
+ env_file=None,
42
+ case_sensitive=False,
43
+ extra="ignore",
44
+ populate_by_name=True,
45
+ )
46
+
47
+ api_key: str | None = Field(default=None, alias="POLI_PAGE_API_KEY")
48
+ base_url: str | None = Field(default=None, alias="POLI_PAGE_BASE_URL")
49
+ timeout: float | None = Field(default=None, alias="POLI_PAGE_TIMEOUT")
50
+ max_retries: int | None = Field(default=None, alias="POLI_PAGE_MAX_RETRIES")
51
+ retry_delay: float | None = Field(default=None, alias="POLI_PAGE_RETRY_DELAY")
52
+
53
+ @field_validator("api_key")
54
+ @classmethod
55
+ def _validate_api_key_shape(cls, v: str | None) -> str | None:
56
+ if v is None or v == "":
57
+ return None
58
+ _warn_if_malformed(v)
59
+ return v
60
+
61
+ @model_validator(mode="after")
62
+ def _validate_env_fallback_key(self) -> PoliPageSettings:
63
+ # With no api_key (e.g. an explicit None or "" that overrides the env var),
64
+ # the client is built without one and the SDK reads POLI_PAGE_API_KEY itself.
65
+ if self.api_key is None:
66
+ env_key = os.environ.get("POLI_PAGE_API_KEY")
67
+ if env_key:
68
+ _warn_if_malformed(env_key)
69
+ return self
70
+
71
+ @field_validator("timeout")
72
+ @classmethod
73
+ def _validate_timeout(cls, v: float | None) -> float | None:
74
+ if v is not None and not (0 < v <= 600):
75
+ raise ValueError("POLI_PAGE_TIMEOUT must be > 0 and <= 600 seconds.")
76
+ return v
77
+
78
+ @field_validator("max_retries")
79
+ @classmethod
80
+ def _validate_max_retries(cls, v: int | None) -> int | None:
81
+ if v is not None and not (0 <= v <= 10):
82
+ raise ValueError("POLI_PAGE_MAX_RETRIES must be between 0 and 10.")
83
+ return v
84
+
85
+ @field_validator("retry_delay")
86
+ @classmethod
87
+ def _validate_retry_delay(cls, v: float | None) -> float | None:
88
+ if v is not None and not (0 <= v <= 30):
89
+ raise ValueError("POLI_PAGE_RETRY_DELAY must be between 0 and 30 seconds.")
90
+ return v
@@ -0,0 +1,47 @@
1
+ """One call to set up the integration on an app: client lifespan and error handler."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ from contextlib import asynccontextmanager
7
+ from typing import Any
8
+
9
+ from fastapi import FastAPI
10
+ from poli_page import PoliPageError
11
+
12
+ from poli_page_fastapi.exceptions import poli_page_exception_handler
13
+ from poli_page_fastapi.lifespan import poli_page_lifespan
14
+
15
+
16
+ def setup_poli_page(app: FastAPI, *, error_handler: bool = True) -> None:
17
+ """Set up Poli Page on `app`. Call it once, before the app starts.
18
+
19
+ - Wraps the app's lifespan in `poli_page_lifespan`: the client is built at
20
+ startup and closed at shutdown. The app's own lifespan (or its startup and
21
+ shutdown handlers) still runs, inside it.
22
+ - Registers `poli_page_exception_handler` for `PoliPageError`, unless
23
+ `error_handler=False`: a route that lets a `PoliPageError` through answers
24
+ its `to_payload()` JSON with its status (500 when it has none).
25
+
26
+ Raises `RuntimeError` once the app has started: Starlette copies the exception
27
+ handlers when it builds its middleware stack, on the first ASGI call, so a later
28
+ handler would never run.
29
+
30
+ Usage:
31
+
32
+ app = FastAPI()
33
+ setup_poli_page(app)
34
+ """
35
+ if app.middleware_stack is not None:
36
+ raise RuntimeError("Call setup_poli_page(app) before the app starts.")
37
+ if error_handler:
38
+ app.add_exception_handler(PoliPageError, poli_page_exception_handler)
39
+
40
+ app_lifespan = app.router.lifespan_context
41
+
42
+ @asynccontextmanager
43
+ async def lifespan(lifespan_app: Any) -> AsyncIterator[Any]:
44
+ async with poli_page_lifespan(lifespan_app), app_lifespan(lifespan_app) as state:
45
+ yield state
46
+
47
+ app.router.lifespan_context = lifespan
@@ -0,0 +1,281 @@
1
+ Metadata-Version: 2.5
2
+ Name: poli-page-fastapi
3
+ Version: 0.13.0
4
+ Summary: FastAPI integration for the Poli Page PDF rendering API
5
+ Project-URL: Homepage, https://poli.page
6
+ Project-URL: Documentation, https://docs.poli.page/reference/sdk/
7
+ Project-URL: Source, https://github.com/poli-page/fastapi
8
+ Project-URL: Issues, https://github.com/poli-page/fastapi/issues
9
+ Project-URL: Changelog, https://github.com/poli-page/fastapi/blob/main/CHANGELOG.md
10
+ Project-URL: Release-Notes, https://github.com/poli-page/fastapi/releases
11
+ Author: Poli Page
12
+ License: MIT
13
+ License-File: LICENSE
14
+ Keywords: fastapi,html,pdf,poli-page,rendering,starlette,template
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Environment :: Web Environment
17
+ Classifier: Framework :: AsyncIO
18
+ Classifier: Framework :: FastAPI
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
28
+ Requires-Dist: anyio>=3.7
29
+ Requires-Dist: fastapi<1.0,>=0.100
30
+ Requires-Dist: poli-page<0.14,>=0.13
31
+ Requires-Dist: pydantic-settings<3,>=2.0
32
+ Requires-Dist: pydantic<3,>=2.0
33
+ Provides-Extra: dev
34
+ Requires-Dist: build>=1; extra == 'dev'
35
+ Requires-Dist: httpx>=0.25; extra == 'dev'
36
+ Requires-Dist: mypy>=1.10; extra == 'dev'
37
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
38
+ Requires-Dist: pytest-mock>=3.12; extra == 'dev'
39
+ Requires-Dist: pytest>=8; extra == 'dev'
40
+ Requires-Dist: python-dotenv>=1.0; extra == 'dev'
41
+ Requires-Dist: respx>=0.21; extra == 'dev'
42
+ Requires-Dist: ruff>=0.6; extra == 'dev'
43
+ Requires-Dist: twine>=7; extra == 'dev'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # poli-page-fastapi
47
+
48
+ > Render Poli Page documents from FastAPI endpoints.
49
+
50
+ ## About
51
+
52
+ This package exposes the Poli Page Python SDK as a FastAPI dependency: a memoised client factory you inject with `Depends()`, Starlette response subclasses that ship the correct PDF headers, and a pydantic-settings reader for `POLI_PAGE_*` env vars. It is a thin wrapper around [`poli-page`](https://pypi.org/project/poli-page/) — the SDK owns transport, retries, error classification, and stream chunking.
53
+
54
+ **When to use this:**
55
+
56
+ - You return generated PDFs from FastAPI routes and want `Depends()` instead of a hand-rolled global client.
57
+ - You want correct `Content-Type`, RFC 5987 `Content-Disposition`, and `Cache-Control` headers without writing them yourself.
58
+ - You want exceptions raised by the SDK to surface as typed JSON responses.
59
+
60
+ **When not to:**
61
+
62
+ - You are not on FastAPI — use [`poli-page`](https://pypi.org/project/poli-page/) directly, or the integration for your framework.
63
+ - You need a CLI command, an `APIRoute` subclass, or an automatic OpenAPI extension — this package ships none of those by design.
64
+
65
+ ## Requirements
66
+
67
+ - Python 3.11, 3.12, or 3.13
68
+ - FastAPI `>=0.100,<1.0`
69
+ - Pydantic v2 and pydantic-settings v2
70
+ - The `poli-page` Python SDK 0.13.x (installed with the package, `poli-page>=0.13,<0.14`)
71
+
72
+ ## Install
73
+
74
+ ```bash
75
+ pip install poli-page-fastapi
76
+ ```
77
+
78
+ This installs the `poli-page` SDK 0.13.x with it.
79
+
80
+ Set the API key in your environment before the app starts:
81
+
82
+ ```bash
83
+ # .env (or your shell)
84
+ POLI_PAGE_API_KEY=pp_sandbox_...
85
+ ```
86
+
87
+ Get a key at [app.poli.page/settings/api-keys](https://app.poli.page/settings/api-keys). The package does not call `load_dotenv()` for you — load the file yourself, or rely on pydantic-settings' `SettingsConfigDict(env_file=...)`.
88
+
89
+ ## API keys
90
+
91
+ A key is `pp_{environment}_{32 lowercase hex}` and belongs to one environment of your organization. The key alone selects the environment, and so which published copy of a project renders: render inputs carry no version.
92
+
93
+ | Environment | Key | Watermark | Counted |
94
+ | ------------------------------------- | -------------- | --------- | ------- |
95
+ | `sandbox` (every org) | `pp_sandbox_…` | yes | no |
96
+ | `live` (every org, deletable on Pro+) | `pp_live_…` | no | yes |
97
+ | created on Pro+ (e.g. `staging`) | `pp_staging_…` | no | yes |
98
+
99
+ "Counted" means the render counts toward the organization's monthly PDF quota.
100
+
101
+ The API is the only authority on keys. This package checks only that `POLI_PAGE_API_KEY` is set and not empty. A value that does not match `pp_{environment}_{32 lowercase hex}` logs one warning through the `poli_page_fastapi.settings` logger, which names the expected format and shows no part of the key, and the client starts anyway: the API answers `401 INVALID_API_KEY` (or `401 MISSING_API_KEY` for a value without `pp_`) if the key is not valid. A key passed explicitly (`PoliPageSettings(api_key=…)`) gets the same check. When that explicit value is `None` or empty, the client is built without a key and the SDK reads `POLI_PAGE_API_KEY` itself, so that value is checked instead.
102
+
103
+ ## Quick start
104
+
105
+ ```python
106
+ # main.py
107
+ from typing import Annotated
108
+
109
+ from fastapi import Depends, FastAPI
110
+ from poli_page import PoliPage
111
+ from poli_page_fastapi import PdfResponse, get_poli_page_client, setup_poli_page
112
+
113
+ app = FastAPI()
114
+ setup_poli_page(app) # client lifespan + error handler
115
+
116
+ Client = Annotated[PoliPage, Depends(get_poli_page_client)]
117
+
118
+
119
+ @app.get("/invoice/{invoice_id}.pdf", response_class=PdfResponse)
120
+ def invoice_pdf(invoice_id: str, client: Client) -> PdfResponse:
121
+ pdf = client.render.pdf({
122
+ "project": "invoices",
123
+ "template": "monthly",
124
+ "data": {"invoice_id": invoice_id},
125
+ })
126
+ return PdfResponse(pdf, filename=f"invoice-{invoice_id}.pdf")
127
+ ```
128
+
129
+ Run with `uvicorn main:app` and `GET /invoice/42.pdf` returns a PDF with the correct headers. `setup_poli_page(app)` builds the client at startup, closes it at shutdown (your own `lifespan` still runs, inside it), and registers the error handler (see [Errors](#errors)).
130
+
131
+ ## Configuration
132
+
133
+ `PoliPageSettings` reads `POLI_PAGE_*` env vars and maps one-to-one with the SDK's `PoliPage(__init__)` kwargs. Unset fields fall through to the SDK's defaults.
134
+
135
+ | Env var | Field | Type | Notes |
136
+ | ------------------------ | ------------- | ------- | ------------------------------------------- |
137
+ | `POLI_PAGE_API_KEY` | `api_key` | `str` | Required: missing or empty, building the client raises `PoliPageError`. A value that is not `pp_{environment}_{32 lowercase hex}` logs one warning, then the API decides (see [API keys](#api-keys)). |
138
+ | `POLI_PAGE_BASE_URL` | `base_url` | `str` | Override for sandbox or regional endpoints. |
139
+ | `POLI_PAGE_TIMEOUT` | `timeout` | `float` | Per-request timeout in seconds, `(0, 600]`. It also bounds the PDF download: a download that outlasts it raises `DOWNLOAD_FAILED` (answered `500`), not `timeout`. |
140
+ | `POLI_PAGE_MAX_RETRIES` | `max_retries` | `int` | Retries per failed request, `[0, 10]`. |
141
+ | `POLI_PAGE_RETRY_DELAY` | `retry_delay` | `float` | Initial backoff in seconds, `[0, 30]`. |
142
+
143
+ To use explicit settings on a per-router or per-endpoint basis, pass a `PoliPageSettings` instance to `PoliPageDependency`:
144
+
145
+ ```python
146
+ # main.py
147
+ import os
148
+
149
+ from poli_page_fastapi import PoliPageDependency, PoliPageSettings
150
+
151
+ sandbox = PoliPageDependency(
152
+ settings=PoliPageSettings(api_key=os.environ["POLI_PAGE_API_KEY"]),
153
+ )
154
+ ```
155
+
156
+ ## API at a glance
157
+
158
+ | Symbol | Purpose |
159
+ | --------------------------- | ---------------------------------------------------------------------- |
160
+ | `get_poli_page_client` | `@lru_cache` memoised factory — the canonical `Depends(...)` target. |
161
+ | `PoliPageDependency` | Class-based dependency for per-router or per-instance settings. |
162
+ | `PoliPageSettings` | Pydantic-settings reader for `POLI_PAGE_*` env vars. |
163
+ | `PdfResponse` | `Response` subclass for `client.render.pdf` bytes. |
164
+ | `PdfStreamResponse` | `StreamingResponse` subclass for `client.render.pdf_stream(...)`: pass the SDK stream as is, so SDK errors reach the error handler. |
165
+ | `PreviewResponse` | `text/html` response for the stored HTML from `client.documents.preview`. |
166
+ | `DocumentRedirectResponse` | 302/308 redirect to a presigned document URL. |
167
+ | `setup_poli_page` | Sets up an app: the client lifespan and the error handler (on by default). |
168
+ | `poli_page_exception_handler` | The error handler: answers a `PoliPageError` with its `to_payload()` JSON. |
169
+ | `poli_page_lifespan` | ASGI lifespan that warms the client on startup and closes on shutdown. |
170
+
171
+ Full reference: the exports of [`src/poli_page_fastapi/__init__.py`](https://github.com/poli-page/fastapi/blob/main/src/poli_page_fastapi/__init__.py) and their docstrings, and the [SDK reference](https://docs.poli.page/reference/sdk/).
172
+
173
+ ## Errors
174
+
175
+ ### Error handler (on by default)
176
+
177
+ `setup_poli_page(app)` registers `poli_page_exception_handler` for `PoliPageError`. A route that lets an SDK error through answers JSON:
178
+
179
+ - the body is the SDK's `exc.to_payload()`, exactly `{"code", "message", "status", "requestId"}`;
180
+ - the HTTP status is that payload's `status`: the API's status for an API error, `503` for `network_error`, `504` for `timeout`, `502` for `invalid_response` (a `2xx` whose body is not JSON, usually from a proxy between the SDK and the API), and `500` when the error has none, such as `io_error` (`render_to_file` could not write the file) or a `DOWNLOAD_FAILED` without a storage status (the body's `status` is then `null`);
181
+ - `Content-Type: application/json`, with `Cache-Control: no-store, private`.
182
+
183
+ ```json
184
+ {
185
+ "code": "TEMPLATE_NOT_FOUND",
186
+ "message": "Template 'does-not-exist' not found in project 'getting-started'.",
187
+ "status": 404,
188
+ "requestId": "req_..."
189
+ }
190
+ ```
191
+
192
+ Other exceptions are not touched. To handle SDK errors yourself, turn the handler off:
193
+
194
+ ```python
195
+ setup_poli_page(app, error_handler=False)
196
+ ```
197
+
198
+ `FastAPI(lifespan=poli_page_lifespan)` on its own registers no handler: use `setup_poli_page(app)` instead (not both, or the client lifespan runs twice), or register the handler yourself with `app.add_exception_handler(PoliPageError, poli_page_exception_handler)`. Call `setup_poli_page` before the app starts; afterwards it raises `RuntimeError`.
199
+
200
+ For a streamed PDF, pass the SDK stream to `PdfStreamResponse` as is, `PdfStreamResponse(client.render.pdf_stream(input))`, instead of opening it inside a generator: an error raised once the body is streaming comes after the `200` is sent, and no handler can answer it. The response closes the stream when it ends, including when the client disconnects, and before it runs a `background` task. Opening the stream sends the render and the download's first request synchronously, so build the response in a `def` route (FastAPI runs it in its threadpool), or through `run_in_threadpool` in an `async def` route.
201
+
202
+ ### Error types
203
+
204
+ The SDK raises one exception family rooted at `PoliPageError`. The four categories in the shared taxonomy map to these SDK classes:
205
+
206
+ - **Auth** — `AuthenticationError`
207
+ - **Rate limit** — `RateLimitError`
208
+ - **Request rejected** — `BadRequestError`, `UnprocessableEntityError` (4xx subclasses of `APIStatusError`)
209
+ - **Network / transport** — `APIConnectionError`, `APITimeoutError`
210
+
211
+ Two more codes come from the SDK itself: `invalid_response` (`InvalidResponseError`, a `2xx` whose body is not JSON) and `io_error` (a `PoliPageError` from `render_to_file` when it cannot write the file, with the `OSError` as `__cause__`).
212
+
213
+ Catch one in the route when it needs its own answer:
214
+
215
+ ```python
216
+ # main.py
217
+ from fastapi.responses import JSONResponse
218
+ from poli_page import RateLimitError
219
+
220
+
221
+ @app.get("/invoice/{invoice_id}.pdf")
222
+ def invoice_pdf(invoice_id: str, client: Client) -> PdfResponse:
223
+ try:
224
+ pdf = client.render.pdf({"project": "...", "template": "...", "data": {}})
225
+ except RateLimitError as exc:
226
+ return JSONResponse(
227
+ status_code=429,
228
+ content={"retry_after": exc.response.headers.get("Retry-After")},
229
+ )
230
+ return PdfResponse(pdf, filename=f"invoice-{invoice_id}.pdf")
231
+ ```
232
+
233
+ ## Example app
234
+
235
+ [`example-app/`](https://github.com/poli-page/fastapi/tree/main/example-app) is a self-contained FastAPI app with an interactive dashboard at `GET /`. It exercises every SDK method — `render.pdf`, `render.pdf_stream`, `render.document`, document retrieval, `documents.preview`, thumbnails, and deletion — and demonstrates `setup_poli_page()`, `Depends()`, the response helpers and the default error handler (`GET /errors/not-found` answers `404 TEMPLATE_NOT_FOUND`). Set `POLI_PAGE_API_KEY` to a sandbox key (`pp_sandbox_…`); `POLI_PAGE_BASE_URL` is optional.
236
+
237
+ ```bash
238
+ cd example-app
239
+ uv sync
240
+ uv run uvicorn main:app --reload --port 8000
241
+ ```
242
+
243
+ Open <http://localhost:8000>.
244
+
245
+ ## Going further
246
+
247
+ The following deep dives are forthcoming under `docs/`:
248
+
249
+ - `docs/lifespan.md` — wiring `poli_page_lifespan` by hand instead of `setup_poli_page`.
250
+ - `docs/async.md` — calling the sync client from `async def` routes via `run_in_threadpool`, and the path to the native `AsyncPoliPage`.
251
+ - `docs/testing.md` — overriding `get_poli_page_client` with `app.dependency_overrides`, and the `TestClient` context-manager requirement.
252
+ - `docs/errors.md` — the full status mapping the global exception handler applies.
253
+ - `docs/responses.md` — RFC 5987 filename encoding, `inline=True`, and streaming responses.
254
+
255
+ ## Compatibility
256
+
257
+ | Package version | `poli-page` SDK | FastAPI | Python |
258
+ | --------------- | --------------- | ---------------------- | ------------------- |
259
+ | 0.13.x | 0.13.x | `^0.100`, `^0.110` | 3.11, 3.12, 3.13 |
260
+
261
+ Tested against the FastAPI versions listed above; other 0.x releases in that range are expected to work. The package shares its major.minor with the Poli Page API and requires the SDK of the same minor: `poli-page>=0.13,<0.14`.
262
+
263
+ ## Contributing
264
+
265
+ Run the checks CI runs from the repository root: `uv sync --all-extras`, then `uv run ruff check .`, `uv run ruff format --check .`, `uv run mypy src tests example-app/tests` and `uv run pytest tests/unit`.
266
+
267
+ ### Contract tests
268
+
269
+ `example-app/tests/test_contract.py` runs the integration cases (`kind: "impl"`) of the [Poli Page API contract](https://github.com/poli-page/api-contract) against the example app: a local server plays the API, the app's SDK points at it through `POLI_PAGE_BASE_URL`, and FastAPI's `TestClient` checks each answer. CI runs them against the contract version pinned in `.github/workflows/ci.yml`. Locally:
270
+
271
+ ```bash
272
+ cd example-app
273
+ uv sync
274
+ POLI_CONTRACT=<path to contract.json> uv run pytest
275
+ ```
276
+
277
+ Without `POLI_CONTRACT` the test is skipped (in CI it fails). `example-app/tests/contract-skip.json` lists the cases allowed to fail, each with its reason.
278
+
279
+ ## License
280
+
281
+ Released under the MIT License — see [LICENSE](https://github.com/poli-page/fastapi/blob/main/LICENSE).
@@ -0,0 +1,14 @@
1
+ poli_page_fastapi/__init__.py,sha256=bQ01nFPkc1NnG2xqrKX6ppQyOhVQ9VU0cIhieI8ZayE,900
2
+ poli_page_fastapi/_headers.py,sha256=-kEUWncgwS5ldK8Opfz4J_gNTZSCb3XEUcaFyGCiCc4,1642
3
+ poli_page_fastapi/_version.py,sha256=DgpLNbv0e1LIEOOe54Db8_390i9pelMEFEnsBsNmyhA,23
4
+ poli_page_fastapi/dependencies.py,sha256=4zgpUedJCJDHo1amjx-xWN1MpcowPHo4onRvWN_B6Lk,2237
5
+ poli_page_fastapi/exceptions.py,sha256=Zhl2Eb_EwwjOrhiSe8Kh2fXjyX21TTNQ3XpLF3wS9zo,1355
6
+ poli_page_fastapi/lifespan.py,sha256=dJHW9ksQFO55vsGto8cZC-IW84Sr7Sdfz-t823xHCgY,686
7
+ poli_page_fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ poli_page_fastapi/responses.py,sha256=bgCo8VdVjWsBdmkV3XF-SSraOSBZi3-O-r71LIxNHC8,6965
9
+ poli_page_fastapi/settings.py,sha256=0BJdUlmY868fkB047mKJUPzSBrY7o23wqZmDX0twmME,3385
10
+ poli_page_fastapi/setup.py,sha256=bqGxp5rYgTxJHy4GX0XyzMnzPrXqaWWREzP6Cn3ntJk,1795
11
+ poli_page_fastapi-0.13.0.dist-info/METADATA,sha256=Ke_cqyF7kb5M8OFoUvFYDZiVrvk561cHGhomxEc_WjM,15296
12
+ poli_page_fastapi-0.13.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ poli_page_fastapi-0.13.0.dist-info/licenses/LICENSE,sha256=dCix9ET3uX7WpcV6_xbc-D0RnW7jP3FrE49nx685J9k,1066
14
+ poli_page_fastapi-0.13.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Poli Page
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.