prettyopenapi 0.1.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.
Files changed (35) hide show
  1. prettyopenapi/__init__.py +183 -0
  2. prettyopenapi/_ui/assets/index-BhiQ8oHd.js +147 -0
  3. prettyopenapi/_ui/assets/index-PWCwrI2V.css +2 -0
  4. prettyopenapi/_ui/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  5. prettyopenapi/_ui/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  6. prettyopenapi/_ui/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  7. prettyopenapi/_ui/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  8. prettyopenapi/_ui/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  9. prettyopenapi/_ui/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  10. prettyopenapi/_ui/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  11. prettyopenapi/_ui/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  12. prettyopenapi/_ui/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  13. prettyopenapi/_ui/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  14. prettyopenapi/_ui/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  15. prettyopenapi/_ui/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  16. prettyopenapi/_ui/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  17. prettyopenapi/_ui/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  18. prettyopenapi/_ui/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  19. prettyopenapi/_ui/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  20. prettyopenapi/_ui/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  21. prettyopenapi/_ui/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  22. prettyopenapi/_ui/assets/manrope-cyrillic-wght-normal-Dvxsihut.woff2 +0 -0
  23. prettyopenapi/_ui/assets/manrope-greek-wght-normal-DL7QRZyv.woff2 +0 -0
  24. prettyopenapi/_ui/assets/manrope-latin-ext-wght-normal-Ch3YOpNY.woff2 +0 -0
  25. prettyopenapi/_ui/assets/manrope-latin-wght-normal-DHIcAJRg.woff2 +0 -0
  26. prettyopenapi/_ui/assets/manrope-vietnamese-wght-normal-usUDDRr7.woff2 +0 -0
  27. prettyopenapi/_ui/assets/spec-Desh2iqS.js +320 -0
  28. prettyopenapi/_ui/index.html +34 -0
  29. prettyopenapi/py.typed +0 -0
  30. prettyopenapi-0.1.0.dist-info/METADATA +119 -0
  31. prettyopenapi-0.1.0.dist-info/RECORD +35 -0
  32. prettyopenapi-0.1.0.dist-info/WHEEL +5 -0
  33. prettyopenapi-0.1.0.dist-info/licenses/LICENSE +202 -0
  34. prettyopenapi-0.1.0.dist-info/licenses/THIRD_PARTY_LICENSES.md +2680 -0
  35. prettyopenapi-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,183 @@
1
+ """A clean API documentation page for FastAPI.
2
+
3
+ from fastapi import FastAPI
4
+ from prettyopenapi import setup_docs
5
+
6
+ app = FastAPI(docs_url=None)
7
+ setup_docs(app, "/docs")
8
+ """
9
+ import json
10
+ import mimetypes
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from starlette.requests import Request
15
+ from starlette.responses import JSONResponse, RedirectResponse, Response
16
+ from starlette.routing import Match
17
+
18
+ __all__ = ["setup_docs", "PathConflictError", "__version__"]
19
+ __version__ = "0.1.0"
20
+
21
+ _UI_DIR = Path(__file__).resolve().parent / "_ui"
22
+ _NO_CACHE = {"Cache-Control": "no-cache"}
23
+ _TYPES = {
24
+ ".html": "text/html; charset=utf-8",
25
+ ".js": "text/javascript; charset=utf-8",
26
+ ".css": "text/css; charset=utf-8",
27
+ ".json": "application/json",
28
+ ".woff2": "font/woff2",
29
+ ".woff": "font/woff",
30
+ ".svg": "image/svg+xml",
31
+ }
32
+
33
+
34
+ class PathConflictError(RuntimeError):
35
+ """The path asked for is already served by the application (for example by FastAPI's own Swagger UI)."""
36
+
37
+
38
+ def _normalize(path: str) -> str:
39
+ """`docs`, `/docs` and `/docs/` all mean `/docs`. The root is the empty string."""
40
+ clean = path.strip().strip("/")
41
+ return f"/{clean}" if clean else ""
42
+
43
+
44
+ def _inline_json(value: Any) -> str:
45
+ """JSON that is safe inside a <script> element: `<` cannot close the tag, U+2028/9 cannot end the line."""
46
+ text = json.dumps(value, ensure_ascii=False)
47
+ return text.replace("<", "\\u003c").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
48
+
49
+
50
+ def _read_ui() -> Tuple[str, Dict[str, bytes]]:
51
+ index = _UI_DIR / "index.html"
52
+ if not index.is_file():
53
+ raise RuntimeError(f"prettyopenapi: the built interface is missing in {_UI_DIR}. Reinstall the package.")
54
+ files = {
55
+ p.relative_to(_UI_DIR).as_posix(): p.read_bytes()
56
+ for p in sorted(_UI_DIR.rglob("*"))
57
+ if p.is_file() and p.name != "index.html"
58
+ }
59
+ return index.read_text(encoding="utf-8"), files
60
+
61
+
62
+ def _find_conflict(app: Any, paths: List[str]) -> Optional[Tuple[str, Any]]:
63
+ """The first of our paths that an existing route would answer to, with that route.
64
+
65
+ It asks the routes themselves, so path parameters, catch-alls (`/{rest:path}`) and mounted apps count too.
66
+ Starlette serves the first route that matches, so a match here means the page would never be reached.
67
+ """
68
+ for path in paths:
69
+ scope = {"type": "http", "method": "GET", "path": path, "root_path": "", "headers": [], "path_params": {}}
70
+ for route in app.router.routes:
71
+ try:
72
+ match, _ = route.matches(scope)
73
+ except Exception: # a route kind that needs more of the scope: not worth failing for
74
+ continue
75
+ if match == Match.FULL:
76
+ return path, route
77
+ return None
78
+
79
+
80
+ def _conflict_message(app: Any, path: str, route: Any, base: str) -> str:
81
+ route_path = getattr(route, "path", None)
82
+ shown = route_path if route_path is not None else type(route).__name__
83
+ msg = f"prettyopenapi: cannot serve the docs at '{base or '/'}': the URL '{path}' is already taken by the route '{shown}'."
84
+ hints = []
85
+ if route_path is not None and route_path == getattr(app, "docs_url", None):
86
+ hints.append("That is FastAPI's own Swagger UI: pass docs_url=None to FastAPI(...) to replace it")
87
+ elif route_path is not None and route_path == getattr(app, "redoc_url", None):
88
+ hints.append("That is FastAPI's own ReDoc: pass redoc_url=None to FastAPI(...) to replace it")
89
+ hints.append(f"Or choose another path, for example setup_docs(app, '{base or '/docs'}/v2')")
90
+ return msg + " " + ". ".join(hints) + "."
91
+
92
+
93
+ def setup_docs(
94
+ app: Any,
95
+ path: str = "/docs",
96
+ *,
97
+ title: Optional[str] = None,
98
+ lang: Optional[str] = None,
99
+ theme: Optional[str] = None,
100
+ base_url: Optional[str] = None,
101
+ ) -> None:
102
+ """Serves the documentation page at `path` and the OpenAPI document at `<path>/openapi.json`.
103
+
104
+ Call it after the routers are included, so the conflict check sees every route.
105
+
106
+ Args:
107
+ app: The FastAPI application.
108
+ path: Where the page lives. `docs`, `/docs` and `/docs/` mean the same.
109
+ title: Replaces `info.title` in the page and the browser tab.
110
+ lang: `"en"` or `"ru"`. The language the page opens in; a language the reader picked earlier wins.
111
+ theme: The theme the page opens in, for example `"nord"`. The reader's choice wins.
112
+ base_url: Where "Try it" sends requests. An absolute URL. By default: the `servers` of the document
113
+ (FastAPI adds `root_path` there), and failing that, the address the page is served from.
114
+
115
+ Raises:
116
+ PathConflictError: the path (or a file under it) is already served by another route, for example
117
+ FastAPI's own Swagger UI at `/docs`.
118
+ """
119
+ if not (hasattr(app, "openapi") and hasattr(app, "add_api_route") and hasattr(app, "router")):
120
+ raise TypeError("prettyopenapi: setup_docs() needs a FastAPI application.")
121
+ if lang not in (None, "en", "ru"):
122
+ raise ValueError("prettyopenapi: lang must be 'en' or 'ru'.")
123
+
124
+ base = _normalize(path)
125
+ index_html, files = _read_ui()
126
+ if "<head>" not in index_html:
127
+ raise RuntimeError("prettyopenapi: index.html has no <head>.")
128
+
129
+ config: Dict[str, Any] = {"specUrl": "./openapi.json"}
130
+ for key, value in (("title", title), ("lang", lang), ("theme", theme), ("baseUrl", base_url)):
131
+ if value is not None:
132
+ config[key] = value
133
+ page = index_html.replace("<head>", f"<head><script>window.__API_BUILDER__={_inline_json(config)}</script>", 1)
134
+
135
+ urls = [f"{base}/", f"{base}/index.html", f"{base}/openapi.json", *(f"{base}/{rel}" for rel in files)]
136
+ if base:
137
+ urls.append(base)
138
+ conflict = _find_conflict(app, urls)
139
+ if conflict:
140
+ raise PathConflictError(_conflict_message(app, conflict[0], conflict[1], base))
141
+
142
+ def add(url: str, endpoint: Any) -> None:
143
+ app.add_api_route(url, endpoint, methods=["GET"], include_in_schema=False)
144
+
145
+ # The page uses relative links, so it must be opened at ".../docs/". A relative redirect also works
146
+ # when a proxy mounts the application under a prefix.
147
+ if base:
148
+ name = base.rsplit("/", 1)[1]
149
+
150
+ async def redirect(request: Request):
151
+ query = request.url.query
152
+ return RedirectResponse(f"{name}/{'?' + query if query else ''}", status_code=302)
153
+
154
+ add(base, redirect)
155
+
156
+ async def index():
157
+ return Response(page, media_type=_TYPES[".html"], headers=_NO_CACHE)
158
+
159
+ async def spec(request: Request):
160
+ schema = app.openapi()
161
+ # The same thing FastAPI does for its own /openapi.json: behind a proxy, `root_path` is a server.
162
+ root_path = request.scope.get("root_path", "").rstrip("/")
163
+ if root_path and getattr(app, "root_path_in_servers", True):
164
+ if root_path not in [s.get("url") for s in schema.get("servers", [])]:
165
+ schema = {**schema, "servers": [{"url": root_path}, *schema.get("servers", [])]}
166
+ return JSONResponse(schema, headers=_NO_CACHE)
167
+
168
+ def static(body: bytes, rel: str) -> Any:
169
+ suffix = Path(rel).suffix
170
+ media_type = _TYPES.get(suffix) or mimetypes.guess_type(rel)[0] or "application/octet-stream"
171
+ # Files under assets/ have the content hash in their name and never change.
172
+ cache = "public, max-age=31536000, immutable" if rel.startswith("assets/") else "public, max-age=3600"
173
+
174
+ async def endpoint():
175
+ return Response(body, media_type=media_type, headers={"Cache-Control": cache})
176
+
177
+ return endpoint
178
+
179
+ add(f"{base}/", index)
180
+ add(f"{base}/index.html", index)
181
+ add(f"{base}/openapi.json", spec)
182
+ for rel, body in files.items():
183
+ add(f"{base}/{rel}", static(body, rel))