{"prefix": "\"\"\"Check release-notes.md and add today's date to the latest release header if missing.\"\"\"\n\nimport re\nimport sys\nfrom datetime import date\n\nRELEASE_NOTES_FILE = \"docs/en/docs/release-notes.md\"\nRELEASE_HEADER_PATTERN = re.compile(r\"^## (\\d+\\.\\d+\\.\\d+)\\s*(\\(.*\\))?\\s*$\")\n\n\ndef main() -> None:\n with open(RELEASE_NOTES_FILE) as f:\n lines = f.readlines()\n\n for i, line in enumerate(lines):\n match = RELEASE_HEADER_PATTERN.match(line)\n if not match:\n continue\n\n version = ", "suffix": "es[i] = f\"## {version} ({today})\\n\"\n print(f\"Added date: {version} ({today})\")\n\n with open(RELEASE_NOTES_FILE, \"w\") as f:\n f.writelines(lines)\n sys.exit(0)\n\n print(\"No release header found\")\n sys.exit(1)\n\n\nif __name__ ", "middle": "match.group(1)\n date_part = match.group(2)\n\n if date_part:\n print(f\"Latest release {version} already has a date: {date_part}\")\n sys.exit(0)\n\n today = date.today().isoformat()\n lin", "meta": {"filepath": "scripts/add_latest_release_date.py", "language": "python", "file_size": 1023, "cut_index": 512, "middle_length": 229}}
{"prefix": "ort BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n github_repository: str\n github_token: SecretStr\n deploy_url: str | None = None\n commit_sha: str\n run_id: int\n state: Literal[\"pending\", \"success\", \"error\"] = \"pending\"\n\n\nclass LinkData(BaseModel):\n previous_link: str\n preview_link: str\n en_link: str | None = None\n\n\ndef main() -> None:\n logging.basicConfig(level=logging.INFO)\n settings = Settings()\n\n logging.info(f\"Using co", "suffix": ".sha == settings.commit_sha), None\n )\n if not use_pr:\n logging.error(f\"No PR found for hash: {settings.commit_sha}\")\n return\n commits = list(use_pr.get_commits())\n current_commit = [c for c in commits if c.sha == settings.commit_s", "middle": "nfig: {settings.model_dump_json()}\")\n g = Github(auth=Auth.Token(settings.github_token.get_secret_value()))\n repo = g.get_repo(settings.github_repository)\n use_pr = next(\n (pr for pr in repo.get_pulls() if pr.head", "meta": {"filepath": "scripts/deploy_docs_status.py", "language": "python", "file_size": 4552, "cut_index": 614, "middle_length": 229}}
{"prefix": "ment.md\",\n \"contributing.md\",\n \"translations.md\",\n)\n\ndocs_path = Path(\"docs\")\nen_docs_path = Path(\"docs/en\")\nen_config_path: Path = en_docs_path / mkdocs_name\nsite_path = Path(\"site\").absolute()\nzensical_src_path = Path(\"site_zensical_src\").absolute()\n\nheader_pattern = re.compile(r\"^(#{1,6}) (.+?)(?:\\s*\\{\\s*(#.*)\\s*\\})?\\s*$\")\nheader_with_permalink_pattern = re.compile(r\"^(#{1,6}) (.+?)(\\s*\\{\\s*#.*\\s*\\})\\s*$\")\ncode_block3_pattern = re.compile(r\"^\\s*```\")\ncode_block4_pattern = re.compile(r\"^\\s*````\")\n\n\n", "suffix": "md_link_pattern.sub(r\"\\1\", text)\n\n\nclass VisibleTextExtractor(HTMLParser):\n \"\"\"Extract visible text from a string with HTML tags.\"\"\"\n\n def __init__(self):\n super().__init__()\n self.text_parts = []\n\n def handle_data(self, data):\n ", "middle": "# Pattern to match markdown links: [text](url) → text\nmd_link_pattern = re.compile(r\"\\[([^\\]]+)\\]\\([^)]+\\)\")\n\n\ndef strip_markdown_links(text: str) -> str:\n \"\"\"Replace markdown links with just their visible text.\"\"\"\n return ", "meta": {"filepath": "scripts/docs.py", "language": "python", "file_size": 30330, "cut_index": 1331, "middle_length": 229}}
{"prefix": " BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\ngithub_graphql_url = \"https://api.github.com/graphql\"\n\n\nsponsors_query = \"\"\"\nquery Q($after: String) {\n user(login: \"tiangolo\") {\n sponsorshipsAsMaintainer(first: 100, after: $after) {\n edges {\n cursor\n node {\n sponsorEntity {\n ... on Organization {\n login\n avatarUrl\n url\n }\n ... on User {\n login\n avatarUrl\n ", "suffix": "tr\n\n\nclass Tier(BaseModel):\n name: str\n monthlyPriceInDollars: float\n\n\nclass SponsorshipAsMaintainerNode(BaseModel):\n sponsorEntity: SponsorEntity\n tier: Tier\n\n\nclass SponsorshipAsMaintainerEdge(BaseModel):\n cursor: str\n node: Sponsorship", "middle": " url\n }\n }\n tier {\n name\n monthlyPriceInDollars\n }\n }\n }\n }\n }\n}\n\"\"\"\n\n\nclass SponsorEntity(BaseModel):\n login: str\n avatarUrl: str\n url: s", "meta": {"filepath": "scripts/sponsors.py", "language": "python", "file_size": 6247, "cut_index": 716, "middle_length": 229}}
{"prefix": "ocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n browser = playwright.chromium.launch(headless=False)\n context = browser.new_context()\n page = context.new_page()\n ", "suffix": " # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/query-param-models/image01.png\")\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fastapi\", \"run\", \"docs_src/query_p", "middle": " page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"GET /items/ Read Items\").click()\n page.get_by_role(\"button\", name=\"Try it out\").click()\n page.get_by_role(\"heading\", name=\"Servers\").click()\n ", "meta": {"filepath": "scripts/playwright/query_param_models/image01.py", "language": "python", "file_size": 1322, "cut_index": 524, "middle_length": 229}}
{"prefix": "aywright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"Item\", exact=True).click()\n page.set_viewport_size({\"width\": 960, \"height\": 700})\n # Manua", "suffix": "path=\"docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png\"\n )\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"uvicorn\", \"docs_src.separate_openapi_schemas.tutorial002:app\"]\n)\ntry:\n w", "middle": "lly add the screenshot\n page.screenshot(\n ", "meta": {"filepath": "scripts/playwright/separate_openapi_schemas/image05.py", "language": "python", "file_size": 984, "cut_index": 582, "middle_length": 52}}
{"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_header_permalinks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_level_mismatch_1.md\")],\n indirect=True,\n)\ndef test_level_mismatch_1(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/", "suffix": ").read_text(\"utf-8\")\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Header levels do not match between document and original docum", "middle": "doc.md\"],\n )\n assert result.exit_code == 1\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(\n f\"{data_path}/translated_doc_level_mismatch_1.md\"\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_level_mismatch.py", "language": "python", "file_size": 1999, "cut_index": 537, "middle_length": 229}}
{"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_markdown_links/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n asse", "suffix": " )\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Number of markdown links does not match the number \"\n \"in the original ", "middle": "rt result.exit_code == 1, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_number_gt.md\").read_text(\n \"utf-8\"\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_markdown_links/test_mkd_links_number_mismatch.py", "language": "python", "file_size": 1911, "cut_index": 537, "middle_length": 229}}
{"prefix": "wordRequestForm,\n SecurityScopes,\n)\nfrom jwt.exceptions import InvalidTokenError\nfrom pwdlib import PasswordHash\nfrom pydantic import BaseModel, ValidationError\n\n# to get a string like this run:\n# openssl rand -hex 32\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\n\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@example.com\",\n \"hashed_p", "suffix": " \"email\": \"alicechains@example.com\",\n \"hashed_password\": \"$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE\",\n \"disabled\": True,\n },\n}\n\n\nclass Token(BaseModel):\n access_token: str\n ", "middle": "assword\": \"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc\",\n \"disabled\": False,\n },\n \"alice\": {\n \"username\": \"alice\",\n \"full_name\": \"Alice Chains\",\n ", "meta": {"filepath": "docs_src/security/tutorial005_py310.py", "language": "python", "file_size": 5418, "cut_index": 716, "middle_length": 229}}
{"prefix": " import Body, FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float | None = None\n\n\n@app.put(\"/items/{item_id}\")\nasync def update_item(\n *,\n item_id: int,\n item: Item = Body(\n openapi_examples={\n \"normal\": {\n \"summary\": \"A normal example\",\n \"description\": \"A **normal** item works correctly.\",\n \"value\": {\n \"name\"", "suffix": "e with converted data\",\n \"description\": \"FastAPI can convert price `strings` to actual `numbers` automatically\",\n \"value\": {\n \"name\": \"Bar\",\n \"price\": \"35.4\",\n },\n ", "middle": ": \"Foo\",\n \"description\": \"A very nice Item\",\n \"price\": 35.4,\n \"tax\": 3.2,\n },\n },\n \"converted\": {\n \"summary\": \"An exampl", "meta": {"filepath": "docs_src/schema_extra_example/tutorial005_py310.py", "language": "python", "file_size": 1348, "cut_index": 524, "middle_length": 229}}
{"prefix": "m collections.abc import AsyncIterable, Iterable\n\nfrom fastapi import FastAPI\nfrom fastapi.sse import EventSourceResponse\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None\n\n\nitems = [\n Item(name=\"Plumbus\", description=\"A multi-purpose household device.\"),\n Item(name=\"Portal Gun\", description=\"A portal opening device.\"),\n Item(name=\"Meeseeks Box\", description=\"A box that summons a Meeseeks.\"),\n]\n\n\n@app.get(\"/items/stream\", response_cla", "suffix": " for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-annotation\", response_class=EventSourceResponse)\nasync def sse_items_no_annotation():\n for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-async-no-annotation\", respon", "middle": "ss=EventSourceResponse)\nasync def sse_items() -> AsyncIterable[Item]:\n for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-async\", response_class=EventSourceResponse)\ndef sse_items_no_async() -> Iterable[Item]:\n", "meta": {"filepath": "docs_src/server_sent_events/tutorial001_py310.py", "language": "python", "file_size": 1112, "cut_index": 515, "middle_length": 229}}
{"prefix": "pi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float = 10.5\n\n\nitems = {\n \"foo\": {\"name\": \"Foo\", \"price\": 50.2},\n \"bar\": {\"name\": \"Bar\", \"description\": \"The Bar fighters\", \"price\": 62, \"tax\": 20.2},\n \"baz\": {\n \"name\": \"Baz\",\n \"description\": \"There goes my baz\",\n \"price\": 50.2,\n \"tax\": 10.5,\n },\n}\n\n\n@app.get(\n \"/items/{item_id}/name\",\n response_mo", "suffix": "response_model_include={\"name\", \"description\"},\n)\nasync def read_item_name(item_id: str):\n return items[item_id]\n\n\n@app.get(\"/items/{item_id}/public\", response_model=Item, response_model_exclude={\"tax\"})\nasync def read_item_public_data(item_id: str):\n ", "middle": "del=Item,\n ", "meta": {"filepath": "docs_src/response_model/tutorial005_py310.py", "language": "python", "file_size": 816, "cut_index": 522, "middle_length": 14}}
{"prefix": "ithub\nfrom pydantic import BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\ngithub_graphql_url = \"https://api.github.com/graphql\"\n\n\nprs_query = \"\"\"\nquery Q($after: String) {\n repository(name: \"fastapi\", owner: \"fastapi\") {\n pullRequests(first: 100, after: $after) {\n edges {\n cursor\n node {\n number\n labels(first: 100) {\n nodes {\n name\n }\n }\n author {\n login\n avatarUrl\n ", "suffix": "arUrl\n url\n }\n state\n }\n }\n }\n }\n }\n }\n}\n\"\"\"\n\n\nclass Author(BaseModel):\n login: str\n avatarUrl: str\n url: str\n\n\nclass LabelNode(BaseModel):\n name: str\n\n\nclass Labels(B", "middle": " url\n }\n title\n createdAt\n lastEditedAt\n updatedAt\n state\n reviews(first:100) {\n nodes {\n author {\n login\n avat", "meta": {"filepath": "scripts/contributors.py", "language": "python", "file_size": 8807, "cut_index": 716, "middle_length": 229}}
{"prefix": " = re.compile(r\"]*)>(.*?)\")\nHTML_LINK_OPEN_TAG_RE = re.compile(r\"]*)>\")\nHTML_ATTR_RE = re.compile(r'(\\w+)\\s*=\\s*([\\'\"])(.*?)\\2')\n\nCODE_BLOCK_LANG_RE = re.compile(r\"^`{3,4}([\\w-]*)\", re.MULTILINE)\n\nSLASHES_COMMENT_RE = re.compile(\n r\"^(?P.*?)(?P.*?)(?P
\n \"\"\"\n return HTMLResponse(content=content)", "middle": "ltipart/form-data\" method=\"post\">\n Hero:\n session.add(hero)\n session.commit()\n session.refresh(hero)\n return hero\n\n\n@app.get", "middle": "nnect_args)\n\n\ndef create_db_and_tables():\n SQLModel.metadata.create_all(engine)\n\n\ndef get_session():\n with Session(engine) as session:\n yield session\n\n\nSessionDep = Annotated[Session, Depends(get_session)]\n\napp = Fas", "meta": {"filepath": "docs_src/sql_databases/tutorial001_an_py310.py", "language": "python", "file_size": 1768, "cut_index": 537, "middle_length": 229}} {"prefix": "FastAPI framework, high performance, easy to learn, fast to code, ready for production\"\"\"\n\n__version__ = \"0.136.3\"\n\nfrom starlette import status as status\n\nfrom .applications import FastAPI as FastAPI\nfrom .background import BackgroundTasks as BackgroundTasks\nfrom .datastructures import UploadFile as UploadFile\nfrom .exceptions import HTTPException as HTTPException\nfrom .exceptions import WebSocketException as WebSocketException\nfrom .param_functions import Body as Body\nfrom .param_functions import Cookie a", "suffix": "from .param_functions import Query as Query\nfrom .param_functions import Security as Security\nfrom .requests import Request as Request\nfrom .responses import Response as Response\nfrom .routing import APIRouter as APIRouter\nfrom .websockets import WebSocket", "middle": "s Cookie\nfrom .param_functions import Depends as Depends\nfrom .param_functions import File as File\nfrom .param_functions import Form as Form\nfrom .param_functions import Header as Header\nfrom .param_functions import Path as Path\n", "meta": {"filepath": "fastapi/__init__.py", "language": "python", "file_size": 1081, "cut_index": 515, "middle_length": 229}} {"prefix": "vent schema matching the OpenAPI 3.2 spec\n# (Section 4.14.4 \"Special Considerations for Server-Sent Events\")\n_SSE_EVENT_SCHEMA: dict[str, Any] = {\n \"type\": \"object\",\n \"properties\": {\n \"data\": {\"type\": \"string\"},\n \"event\": {\"type\": \"string\"},\n \"id\": {\"type\": \"string\"},\n \"retry\": {\"type\": \"integer\", \"minimum\": 0},\n },\n}\n\n\nclass EventSourceResponse(StreamingResponse):\n \"\"\"Streaming response with `text/event-stream` media type.\n\n Use as `response_class=EventSourceRespo", "suffix": "`POST`.\n\n The actual encoding logic lives in the FastAPI routing layer. This class\n serves mainly as a marker and sets the correct `Content-Type`.\n \"\"\"\n\n media_type = \"text/event-stream\"\n\n\ndef _check_single_line(v: str | None, field_name: str) ", "middle": "nse` on a *path operation* that uses `yield`\n to enable Server Sent Events (SSE) responses.\n\n Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible\n with protocols like MCP that stream SSE over ", "meta": {"filepath": "fastapi/sse.py", "language": "python", "file_size": 6848, "cut_index": 716, "middle_length": 229}} {"prefix": "shot\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Items(BaseModel):\n items: dict[str, int]\n\n\n@app.post(\"/foo\")\ndef foo(items: Items):\n return items.items\n\n\nclient = TestClient(app)\n\n\ndef test_additional_properties_post():\n response = client.post(\"/foo\", json={\"items\": {\"foo\": 1, \"bar\": 2}})\n assert response.status_code == 200, response.text\n assert response.json() == {\"foo\": 1, \"bar\": 2}\n\n\ndef test_openapi_schema():\n response = client.get(\"/openapi.json\")\n assert response.sta", "suffix": " \"post\": {\n \"responses\": {\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\"application/json\": {\"schema\": {}}},\n ", "middle": "tus_code == 200, response.text\n assert response.json() == snapshot(\n {\n \"openapi\": \"3.1.0\",\n \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n \"paths\": {\n \"/foo\": {\n ", "meta": {"filepath": "tests/test_additional_properties.py", "language": "python", "file_size": 4238, "cut_index": 614, "middle_length": 229}} {"prefix": "ontextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\n\nitems = {}\n\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n items[\"foo\"] = {\"name\": \"Fighters\"}\n items[\"bar\"] = {\"name\": \"Tenders\"}\n yield\n # clean up items\n items.clear()\n\n\napp = FastAPI(lifespan=lifespan)\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_items(item_id: str):\n return items[item_id]\n\n\ndef test_read_items():\n # Before the lifespan starts, \"items\" is still emp", "suffix": " response = client.get(\"/items/foo\")\n assert response.status_code == 200\n assert response.json() == {\"name\": \"Fighters\"}\n\n # After the requests is done, the items are still there\n assert items == {\"foo\": {\"name\": \"Fighters", "middle": "ty\n assert items == {}\n\n with TestClient(app) as client:\n # Inside the \"with TestClient\" block, the lifespan starts and items added\n assert items == {\"foo\": {\"name\": \"Fighters\"}, \"bar\": {\"name\": \"Tenders\"}}\n\n ", "meta": {"filepath": "docs_src/app_testing/tutorial004_py310.py", "language": "python", "file_size": 1187, "cut_index": 518, "middle_length": 229}} {"prefix": "mport TestClient\n\nfrom .main import app\n\nclient = TestClient(app)\n\n\ndef test_read_item():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 200\n assert response.json() == {\n \"id\": \"foo\",\n \"title\": \"Foo\",\n \"description\": \"There goes my hero\",\n }\n\n\ndef test_read_item_bad_token():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"hailhydra\"})\n assert response.status_code == 400\n assert response.json() == ", "suffix": ": \"Item not found\"}\n\n\ndef test_create_item():\n response = client.post(\n \"/items/\",\n headers={\"X-Token\": \"coneofsilence\"},\n json={\"id\": \"foobar\", \"title\": \"Foo Bar\", \"description\": \"The Foo Barters\"},\n )\n assert response.status", "middle": "{\"detail\": \"Invalid X-Token header\"}\n\n\ndef test_read_nonexistent_item():\n response = client.get(\"/items/baz\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 404\n assert response.json() == {\"detail\"", "meta": {"filepath": "docs_src/app_testing/app_b_py310/test_main.py", "language": "python", "file_size": 1866, "cut_index": 537, "middle_length": 229}} {"prefix": "yping import Annotated\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel\n\nfake_secret_token = \"coneofsilence\"\n\nfake_db = {\n \"foo\": {\"id\": \"foo\", \"title\": \"Foo\", \"description\": \"There goes my hero\"},\n \"bar\": {\"id\": \"bar\", \"title\": \"Bar\", \"description\": \"The bartenders\"},\n}\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n id: str\n title: str\n description: str | None = None\n\n\n@app.get(\"/items/{item_id}\", response_model=Item)\nasync def read_main(item_id: str, x_token: A", "suffix": " not found\")\n return fake_db[item_id]\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, x_token: Annotated[str, Header()]) -> Item:\n if x_token != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")", "middle": "nnotated[str, Header()]):\n if x_token != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n if item_id not in fake_db:\n raise HTTPException(status_code=404, detail=\"Item", "meta": {"filepath": "docs_src/app_testing/app_b_an_py310/main.py", "language": "python", "file_size": 1163, "cut_index": 518, "middle_length": 229}} {"prefix": "astapi import FastAPI\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\n\napp = FastAPI(docs_url=None, redoc_url=None)\n\n\n@app.get(\"/docs\", include_in_schema=False)\nasync def custom_swagger_ui_html():\n return get_swagger_ui_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - Swagger UI\",\n oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,\n swagger_js_url=\"https://unpkg.com/swagger-ui-dist@5/swag", "suffix": "r_ui_oauth2_redirect_html()\n\n\n@app.get(\"/redoc\", include_in_schema=False)\nasync def redoc_html():\n return get_redoc_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - ReDoc\",\n redoc_js_url=\"https://unpkg.com/redoc@2/bundles/", "middle": "ger-ui-bundle.js\",\n swagger_css_url=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\",\n )\n\n\n@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)\nasync def swagger_ui_redirect():\n return get_swagge", "meta": {"filepath": "docs_src/custom_docs_ui/tutorial001_py310.py", "language": "python", "file_size": 1143, "cut_index": 518, "middle_length": 229}} {"prefix": "m fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel\n\nfake_secret_token = \"coneofsilence\"\n\nfake_db = {\n \"foo\": {\"id\": \"foo\", \"title\": \"Foo\", \"description\": \"There goes my hero\"},\n \"bar\": {\"id\": \"bar\", \"title\": \"Bar\", \"description\": \"The bartenders\"},\n}\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n id: str\n title: str\n description: str | None = None\n\n\n@app.get(\"/items/{item_id}\", response_model=Item)\nasync def read_main(item_id: str, x_token: str = Header()):\n if x_to", "suffix": "id]\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, x_token: str = Header()) -> Item:\n if x_token != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n if item.id in fake_db:\n raise HTTPE", "middle": "ken != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n if item_id not in fake_db:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return fake_db[item_", "meta": {"filepath": "docs_src/app_testing/app_b_py310/main.py", "language": "python", "file_size": 1113, "cut_index": 515, "middle_length": 229}} {"prefix": "mport TestClient\n\nfrom .main import app\n\nclient = TestClient(app)\n\n\ndef test_read_item():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 200\n assert response.json() == {\n \"id\": \"foo\",\n \"title\": \"Foo\",\n \"description\": \"There goes my hero\",\n }\n\n\ndef test_read_item_bad_token():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"hailhydra\"})\n assert response.status_code == 400\n assert response.json() == ", "suffix": ": \"Item not found\"}\n\n\ndef test_create_item():\n response = client.post(\n \"/items/\",\n headers={\"X-Token\": \"coneofsilence\"},\n json={\"id\": \"foobar\", \"title\": \"Foo Bar\", \"description\": \"The Foo Barters\"},\n )\n assert response.status", "middle": "{\"detail\": \"Invalid X-Token header\"}\n\n\ndef test_read_nonexistent_item():\n response = client.get(\"/items/baz\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 404\n assert response.json() == {\"detail\"", "meta": {"filepath": "docs_src/app_testing/app_b_an_py310/test_main.py", "language": "python", "file_size": 1866, "cut_index": 537, "middle_length": 229}} {"prefix": "fastapi import FastAPI\n\ndescription = \"\"\"\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n\"\"\"\n\napp = FastAPI(\n title=\"ChimichangApp\",\n description=description,\n summary=\"Deadpool's favorite app. Nuff said.\",\n version=\"0.0.1\",\n terms_of_service=\"http://example.com/terms/\",\n contact={\n \"name\": \"Deadpoolio the Amazing\",\n \"url\": \"http:/", "suffix": "le.com/contact/\",\n \"email\": \"dp@x-force.example.com\",\n },\n license_info={\n \"name\": \"Apache 2.0\",\n \"url\": \"https://www.apache.org/licenses/LICENSE-2.0.html\",\n },\n)\n\n\n@app.get(\"/items/\")\nasync def read_items():\n return [{\"nam", "middle": "/x-force.examp", "meta": {"filepath": "docs_src/metadata/tutorial001_py310.py", "language": "python", "file_size": 805, "cut_index": 517, "middle_length": 14}} {"prefix": "pi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float = 10.5\n\n\nitems = {\n \"foo\": {\"name\": \"Foo\", \"price\": 50.2},\n \"bar\": {\"name\": \"Bar\", \"description\": \"The Bar fighters\", \"price\": 62, \"tax\": 20.2},\n \"baz\": {\n \"name\": \"Baz\",\n \"description\": \"There goes my baz\",\n \"price\": 50.2,\n \"tax\": 10.5,\n },\n}\n\n\n@app.get(\n \"/items/{item_id}/name\",\n response_mo", "suffix": "response_model_include=[\"name\", \"description\"],\n)\nasync def read_item_name(item_id: str):\n return items[item_id]\n\n\n@app.get(\"/items/{item_id}/public\", response_model=Item, response_model_exclude=[\"tax\"])\nasync def read_item_public_data(item_id: str):\n ", "middle": "del=Item,\n ", "meta": {"filepath": "docs_src/response_model/tutorial006_py310.py", "language": "python", "file_size": 816, "cut_index": 522, "middle_length": 14}} {"prefix": "l\n\n\ndef custom_generate_unique_id(route: APIRoute):\n return f\"{route.tags[0]}-{route.name}\"\n\n\napp = FastAPI(generate_unique_id_function=custom_generate_unique_id)\n\n\nclass Item(BaseModel):\n name: str\n price: float\n\n\nclass ResponseMessage(BaseModel):\n message: str\n\n\nclass User(BaseModel):\n username: str\n email: str\n\n\n@app.post(\"/items/\", response_model=ResponseMessage, tags=[\"items\"])\nasync def create_item(item: Item):\n return {\"message\": \"Item received\"}\n\n\n@app.get(\"/items/\", response_mo", "suffix": "):\n return [\n {\"name\": \"Plumbus\", \"price\": 3},\n {\"name\": \"Portal Gun\", \"price\": 9001},\n ]\n\n\n@app.post(\"/users/\", response_model=ResponseMessage, tags=[\"users\"])\nasync def create_user(user: User):\n return {\"message\": \"User received\"}\n", "middle": "del=list[Item], tags=[\"items\"])\nasync def get_items(", "meta": {"filepath": "docs_src/generate_clients/tutorial003_py310.py", "language": "python", "file_size": 914, "cut_index": 606, "middle_length": 52}} {"prefix": "from fastapi import APIRouter, Depends, HTTPException\n\nfrom ..dependencies import get_token_header\n\nrouter = APIRouter(\n prefix=\"/items\",\n tags=[\"items\"],\n dependencies=[Depends(get_token_header)],\n responses={404: {\"description\": \"Not found\"}},\n)\n\n\nfake_items_db = {\"plumbus\": {\"name\": \"Plumbus\"}, \"gun\": {\"name\": \"Portal Gun\"}}\n\n\n@router.get(\"/\")\nasync def read_items():\n return fake_items_db\n\n\n@router.get(\"/{item_id}\")\nasync def read_item(item_id: str):\n if item_id not in fake_items_db:\n ", "suffix": " \"Operation forbidden\"}},\n)\nasync def update_item(item_id: str):\n if item_id != \"plumbus\":\n raise HTTPException(\n status_code=403, detail=\"You can only update the item: plumbus\"\n )\n return {\"item_id\": item_id, \"name\": \"The gr", "middle": " raise HTTPException(status_code=404, detail=\"Item not found\")\n return {\"name\": fake_items_db[item_id][\"name\"], \"item_id\": item_id}\n\n\n@router.put(\n \"/{item_id}\",\n tags=[\"custom\"],\n responses={403: {\"description\":", "meta": {"filepath": "docs_src/bigger_applications/app_an_py310/routers/items.py", "language": "python", "file_size": 1011, "cut_index": 512, "middle_length": 229}} {"prefix": "dantic import BaseModel, EmailStr\n\napp = FastAPI()\n\n\nclass UserIn(BaseModel):\n username: str\n password: str\n email: EmailStr\n full_name: str | None = None\n\n\nclass UserOut(BaseModel):\n username: str\n email: EmailStr\n full_name: str | None = None\n\n\nclass UserInDB(BaseModel):\n username: str\n hashed_password: str\n email: EmailStr\n full_name: str | None = None\n\n\ndef fake_password_hasher(raw_password: str):\n return \"supersecret\" + raw_password\n\n\ndef fake_save_user(user_in: User", "suffix": "_in.password)\n user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)\n print(\"User saved! ..not really\")\n return user_in_db\n\n\n@app.post(\"/user/\", response_model=UserOut)\nasync def create_user(user_in: UserIn):\n user_save", "middle": "In):\n hashed_password = fake_password_hasher(user", "meta": {"filepath": "docs_src/extra_models/tutorial001_py310.py", "language": "python", "file_size": 905, "cut_index": 547, "middle_length": 52}} {"prefix": "fastapi import FastAPI\nfrom pydantic import BaseModel, EmailStr\n\napp = FastAPI()\n\n\nclass UserBase(BaseModel):\n username: str\n email: EmailStr\n full_name: str | None = None\n\n\nclass UserIn(UserBase):\n password: str\n\n\nclass UserOut(UserBase):\n pass\n\n\nclass UserInDB(UserBase):\n hashed_password: str\n\n\ndef fake_password_hasher(raw_password: str):\n return \"supersecret\" + raw_password\n\n\ndef fake_save_user(user_in: UserIn):\n hashed_password = fake_password_hasher(user_in.password)\n user_in", "suffix": "(**user_in.model_dump(), hashed_password=hashed_password)\n print(\"User saved! ..not really\")\n return user_in_db\n\n\n@app.post(\"/user/\", response_model=UserOut)\nasync def create_user(user_in: UserIn):\n user_saved = fake_save_user(user_in)\n return ", "middle": "_db = UserInDB", "meta": {"filepath": "docs_src/extra_models/tutorial002_py310.py", "language": "python", "file_size": 798, "cut_index": 517, "middle_length": 14}} {"prefix": "FastAPI,\n Query,\n WebSocket,\n WebSocketException,\n status,\n)\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\nhtml = \"\"\"\n\n\n
\n
\n \n