sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
fastapi/fastapi:tests/test_strict_content_type_app_level.py
from fastapi import FastAPI from fastapi.testclient import TestClient app_default = FastAPI() @app_default.post("/items/") async def app_default_post(data: dict): return data app_lax = FastAPI(strict_content_type=False) @app_lax.post("/items/") async def app_lax_post(data: dict): return data client_default = TestClient(app_default) client_lax = TestClient(app_lax) def test_default_strict_rejects_no_content_type(): response = client_default.post("/items/", content='{"key": "value"}') assert response.status_code == 422 def test_default_strict_accepts_json_content_type(): response = client_default.post("/items/", json={"key": "value"}) assert response.status_code == 200 assert response.json() == {"key": "value"} def test_lax_accepts_no_content_type(): response = client_lax.post("/items/", content='{"key": "value"}') assert response.status_code == 200 assert response.json() == {"key": "value"} def test_lax_accepts_json_content_type(): response = client_lax.post("/items/", json={"key": "value"}) assert response.status_code == 200 assert response.json() == {"key": "value"}
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_strict_content_type_app_level.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_strict_content_type_nested.py
from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient # Lax app with nested routers, inner overrides to strict app_nested = FastAPI(strict_content_type=False) # lax app outer_router = APIRouter(prefix="/outer") # inherits lax from app inner_strict = APIRouter(prefix="/strict", strict_content_type=True) inner_default = APIRouter(prefix="/default") @inner_strict.post("/items/") async def inner_strict_post(data: dict): return data @inner_default.post("/items/") async def inner_default_post(data: dict): return data outer_router.include_router(inner_strict) outer_router.include_router(inner_default) app_nested.include_router(outer_router) client_nested = TestClient(app_nested) def test_strict_inner_on_lax_app_rejects_no_content_type(): response = client_nested.post("/outer/strict/items/", content='{"key": "value"}') assert response.status_code == 422 def test_default_inner_inherits_lax_from_app(): response = client_nested.post("/outer/default/items/", content='{"key": "value"}') assert response.status_code == 200 assert response.json() == {"key": "value"} def test_strict_inner_accepts_json_content_type(): response = client_nested.post("/outer/strict/items/", json={"key": "value"}) assert response.status_code == 200 def test_default_inner_accepts_json_content_type(): response = client_nested.post("/outer/default/items/", json={"key": "value"}) assert response.status_code == 200 # Strict app -> lax outer router -> strict inner router app_mixed = FastAPI(strict_content_type=True) mixed_outer = APIRouter(prefix="/outer", strict_content_type=False) mixed_inner = APIRouter(prefix="/inner", strict_content_type=True) @mixed_outer.post("/items/") async def mixed_outer_post(data: dict): return data @mixed_inner.post("/items/") async def mixed_inner_post(data: dict): return data mixed_outer.include_router(mixed_inner) app_mixed.include_router(mixed_outer) client_mixed = TestClient(app_mixed) def test_lax_outer_on_strict_app_accepts_no_content_type(): response = client_mixed.post("/outer/items/", content='{"key": "value"}') assert response.status_code == 200 assert response.json() == {"key": "value"} def test_strict_inner_on_lax_outer_rejects_no_content_type(): response = client_mixed.post("/outer/inner/items/", content='{"key": "value"}') assert response.status_code == 422 def test_lax_outer_accepts_json_content_type(): response = client_mixed.post("/outer/items/", json={"key": "value"}) assert response.status_code == 200 def test_strict_inner_on_lax_outer_accepts_json_content_type(): response = client_mixed.post("/outer/inner/items/", json={"key": "value"}) assert response.status_code == 200
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_strict_content_type_nested.py", "license": "MIT License", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_strict_content_type_router_level.py
from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient app = FastAPI() router_lax = APIRouter(prefix="/lax", strict_content_type=False) router_strict = APIRouter(prefix="/strict", strict_content_type=True) router_default = APIRouter(prefix="/default") @router_lax.post("/items/") async def router_lax_post(data: dict): return data @router_strict.post("/items/") async def router_strict_post(data: dict): return data @router_default.post("/items/") async def router_default_post(data: dict): return data app.include_router(router_lax) app.include_router(router_strict) app.include_router(router_default) client = TestClient(app) def test_lax_router_on_strict_app_accepts_no_content_type(): response = client.post("/lax/items/", content='{"key": "value"}') assert response.status_code == 200 assert response.json() == {"key": "value"} def test_strict_router_on_strict_app_rejects_no_content_type(): response = client.post("/strict/items/", content='{"key": "value"}') assert response.status_code == 422 def test_default_router_inherits_strict_from_app(): response = client.post("/default/items/", content='{"key": "value"}') assert response.status_code == 422 def test_lax_router_accepts_json_content_type(): response = client.post("/lax/items/", json={"key": "value"}) assert response.status_code == 200 def test_strict_router_accepts_json_content_type(): response = client.post("/strict/items/", json={"key": "value"}) assert response.status_code == 200 def test_default_router_accepts_json_content_type(): response = client.post("/default/items/", json={"key": "value"}) assert response.status_code == 200
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_strict_content_type_router_level.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_strict_content_type/test_tutorial001.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ "tutorial001_py310", ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.strict_content_type.{request.param}") client = TestClient(mod.app) return client def test_lax_post_without_content_type_is_parsed_as_json(client: TestClient): response = client.post( "/items/", content='{"name": "Foo", "price": 50.5}', ) assert response.status_code == 200, response.text assert response.json() == {"name": "Foo", "price": 50.5} def test_lax_post_with_json_content_type(client: TestClient): response = client.post( "/items/", json={"name": "Foo", "price": 50.5}, ) assert response.status_code == 200, response.text assert response.json() == {"name": "Foo", "price": 50.5} def test_lax_post_with_text_plain_is_still_rejected(client: TestClient): response = client.post( "/items/", content='{"name": "Foo", "price": 50.5}', headers={"Content-Type": "text/plain"}, ) assert response.status_code == 422, response.text
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_strict_content_type/test_tutorial001.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_deprecated_responses.py
import warnings import pytest from fastapi import FastAPI from fastapi.exceptions import FastAPIDeprecationWarning from fastapi.responses import ORJSONResponse, UJSONResponse from fastapi.testclient import TestClient from pydantic import BaseModel class Item(BaseModel): name: str price: float # ORJSON def _make_orjson_app() -> FastAPI: with warnings.catch_warnings(): warnings.simplefilter("ignore", FastAPIDeprecationWarning) app = FastAPI(default_response_class=ORJSONResponse) @app.get("/items") def get_items() -> Item: return Item(name="widget", price=9.99) return app def test_orjson_response_returns_correct_data(): app = _make_orjson_app() client = TestClient(app) with warnings.catch_warnings(): warnings.simplefilter("ignore", FastAPIDeprecationWarning) response = client.get("/items") assert response.status_code == 200 assert response.json() == {"name": "widget", "price": 9.99} def test_orjson_response_emits_deprecation_warning(): with pytest.warns(FastAPIDeprecationWarning, match="ORJSONResponse is deprecated"): ORJSONResponse(content={"hello": "world"}) # UJSON def _make_ujson_app() -> FastAPI: with warnings.catch_warnings(): warnings.simplefilter("ignore", FastAPIDeprecationWarning) app = FastAPI(default_response_class=UJSONResponse) @app.get("/items") def get_items() -> Item: return Item(name="widget", price=9.99) return app def test_ujson_response_returns_correct_data(): app = _make_ujson_app() client = TestClient(app) with warnings.catch_warnings(): warnings.simplefilter("ignore", FastAPIDeprecationWarning) response = client.get("/items") assert response.status_code == 200 assert response.json() == {"name": "widget", "price": 9.99} def test_ujson_response_emits_deprecation_warning(): with pytest.warns(FastAPIDeprecationWarning, match="UJSONResponse is deprecated"): UJSONResponse(content={"hello": "world"})
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_deprecated_responses.py", "license": "MIT License", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_dump_json_fast_path.py
from unittest.mock import patch from fastapi import FastAPI from fastapi.responses import JSONResponse from fastapi.testclient import TestClient from pydantic import BaseModel class Item(BaseModel): name: str price: float app = FastAPI() @app.get("/default") def get_default() -> Item: return Item(name="widget", price=9.99) @app.get("/explicit", response_class=JSONResponse) def get_explicit() -> Item: return Item(name="widget", price=9.99) client = TestClient(app) def test_default_response_class_skips_json_dumps(): """When no response_class is set, the fast path serializes directly to JSON bytes via Pydantic's dump_json and never calls json.dumps.""" with patch( "starlette.responses.json.dumps", wraps=__import__("json").dumps ) as mock_dumps: response = client.get("/default") assert response.status_code == 200 assert response.json() == {"name": "widget", "price": 9.99} mock_dumps.assert_not_called() def test_explicit_response_class_uses_json_dumps(): """When response_class is explicitly set to JSONResponse, the normal path is used and json.dumps is called via JSONResponse.render().""" with patch( "starlette.responses.json.dumps", wraps=__import__("json").dumps ) as mock_dumps: response = client.get("/explicit") assert response.status_code == 200 assert response.json() == {"name": "widget", "price": 9.99} mock_dumps.assert_called_once()
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_dump_json_fast_path.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_custom_response/test_tutorial010.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot @pytest.fixture( name="client", params=[ pytest.param("tutorial010_py310"), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.custom_response.{request.param}") client = TestClient(mod.app) return client def test_get_custom_response(client: TestClient): response = client.get("/items/") assert response.status_code == 200, response.text assert response.text == snapshot("<h1>Items</h1><p>This is a list of items.</p>") def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": { "text/html": {"schema": {"type": "string"}} }, } }, "summary": "Read Items", "operationId": "read_items_items__get", } } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_custom_response/test_tutorial010.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:docs_src/json_base64_bytes/tutorial001_py310.py
from fastapi import FastAPI from pydantic import BaseModel class DataInput(BaseModel): description: str data: bytes model_config = {"val_json_bytes": "base64"} class DataOutput(BaseModel): description: str data: bytes model_config = {"ser_json_bytes": "base64"} class DataInputOutput(BaseModel): description: str data: bytes model_config = { "val_json_bytes": "base64", "ser_json_bytes": "base64", } app = FastAPI() @app.post("/data") def post_data(body: DataInput): content = body.data.decode("utf-8") return {"description": body.description, "content": content} @app.get("/data") def get_data() -> DataOutput: data = "hello".encode("utf-8") return DataOutput(description="A plumbus", data=data) @app.post("/data-in-out") def post_data_in_out(body: DataInputOutput) -> DataInputOutput: return body
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/json_base64_bytes/tutorial001_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:scripts/playwright/json_base64_bytes/image01.py
import subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="POST /data Post Data").click() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/json-base64-bytes/image01.png") # --------------------- context.close() browser.close() process = subprocess.Popen( ["fastapi", "run", "docs_src/json_base64_bytes/tutorial001_py310.py"] ) try: for _ in range(3): try: response = httpx.get("http://localhost:8000/docs") except httpx.ConnectError: time.sleep(1) break with sync_playwright() as playwright: run(playwright) finally: process.terminate()
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/playwright/json_base64_bytes/image01.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:tests/test_tutorial/test_json_base64_bytes/test_tutorial001.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from tests.utils import needs_py310 @pytest.fixture( name="client", params=[pytest.param("tutorial001_py310", marks=needs_py310)], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.json_base64_bytes.{request.param}") client = TestClient(mod.app) return client def test_post_data(client: TestClient): response = client.post( "/data", json={ "description": "A file", "data": "SGVsbG8sIFdvcmxkIQ==", }, ) assert response.status_code == 200, response.text assert response.json() == {"description": "A file", "content": "Hello, World!"} def test_get_data(client: TestClient): response = client.get("/data") assert response.status_code == 200, response.text assert response.json() == {"description": "A plumbus", "data": "aGVsbG8="} def test_post_data_in_out(client: TestClient): response = client.post( "/data-in-out", json={ "description": "A plumbus", "data": "SGVsbG8sIFdvcmxkIQ==", }, ) assert response.status_code == 200, response.text assert response.json() == { "description": "A plumbus", "data": "SGVsbG8sIFdvcmxkIQ==", } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/data": { "get": { "summary": "Get Data", "operationId": "get_data_data_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DataOutput" } } }, } }, }, "post": { "summary": "Post Data", "operationId": "post_data_data_post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/DataInput"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, "/data-in-out": { "post": { "summary": "Post Data In Out", "operationId": "post_data_in_out_data_in_out_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DataInputOutput" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DataInputOutput" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "DataInput": { "properties": { "description": {"type": "string", "title": "Description"}, "data": { "type": "string", "contentEncoding": "base64", "contentMediaType": "application/octet-stream", "title": "Data", }, }, "type": "object", "required": ["description", "data"], "title": "DataInput", }, "DataInputOutput": { "properties": { "description": {"type": "string", "title": "Description"}, "data": { "type": "string", "contentEncoding": "base64", "contentMediaType": "application/octet-stream", "title": "Data", }, }, "type": "object", "required": ["description", "data"], "title": "DataInputOutput", }, "DataOutput": { "properties": { "description": {"type": "string", "title": "Description"}, "data": { "type": "string", "contentEncoding": "base64", "contentMediaType": "application/octet-stream", "title": "Data", }, }, "type": "object", "required": ["description", "data"], "title": "DataOutput", }, "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "ValidationError": { "properties": { "ctx": {"title": "Context", "type": "object"}, "input": {"title": "Input"}, "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_json_base64_bytes/test_tutorial001.py", "license": "MIT License", "lines": 212, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:docs_src/additional_responses/tutorial001_py310.py
from fastapi import FastAPI from fastapi.responses import JSONResponse from pydantic import BaseModel class Item(BaseModel): id: str value: str class Message(BaseModel): message: str app = FastAPI() @app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}}) async def read_item(item_id: str): if item_id == "foo": return {"id": "foo", "value": "there goes my hero"} return JSONResponse(status_code=404, content={"message": "Item not found"})
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/additional_responses/tutorial001_py310.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/additional_responses/tutorial003_py310.py
from fastapi import FastAPI from fastapi.responses import JSONResponse from pydantic import BaseModel class Item(BaseModel): id: str value: str class Message(BaseModel): message: str app = FastAPI() @app.get( "/items/{item_id}", response_model=Item, responses={ 404: {"model": Message, "description": "The item was not found"}, 200: { "description": "Item requested by ID", "content": { "application/json": { "example": {"id": "bar", "value": "The bar tenders"} } }, }, }, ) async def read_item(item_id: str): if item_id == "foo": return {"id": "foo", "value": "there goes my hero"} else: return JSONResponse(status_code=404, content={"message": "Item not found"})
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/additional_responses/tutorial003_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/advanced_middleware/tutorial001_py310.py
from fastapi import FastAPI from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware app = FastAPI() app.add_middleware(HTTPSRedirectMiddleware) @app.get("/") async def main(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/advanced_middleware/tutorial001_py310.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/advanced_middleware/tutorial002_py310.py
from fastapi import FastAPI from fastapi.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() app.add_middleware( TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"] ) @app.get("/") async def main(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/advanced_middleware/tutorial002_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/advanced_middleware/tutorial003_py310.py
from fastapi import FastAPI from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5) @app.get("/") async def main(): return "somebigcontent"
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/advanced_middleware/tutorial003_py310.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/app_testing/app_a_py310/main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/app_testing/app_a_py310/main.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/app_testing/app_a_py310/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/app_testing/app_a_py310/test_main.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:docs_src/app_testing/tutorial001_py310.py
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"} client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/app_testing/tutorial001_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/app_testing/tutorial002_py310.py
from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocket app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"} @app.websocket("/ws") async def websocket(websocket: WebSocket): await websocket.accept() await websocket.send_json({"msg": "Hello WebSocket"}) await websocket.close() def test_read_main(): client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"} def test_websocket(): client = TestClient(app) with client.websocket_connect("/ws") as websocket: data = websocket.receive_json() assert data == {"msg": "Hello WebSocket"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/app_testing/tutorial002_py310.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/app_testing/tutorial003_py310.py
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() items = {} @app.on_event("startup") async def startup_event(): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"} @app.get("/items/{item_id}") async def read_items(item_id: str): return items[item_id] def test_read_items(): with TestClient(app) as client: response = client.get("/items/foo") assert response.status_code == 200 assert response.json() == {"name": "Fighters"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/app_testing/tutorial003_py310.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/app_testing/tutorial004_py310.py
from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.testclient import TestClient items = {} @asynccontextmanager async def lifespan(app: FastAPI): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"} yield # clean up items items.clear() app = FastAPI(lifespan=lifespan) @app.get("/items/{item_id}") async def read_items(item_id: str): return items[item_id] def test_read_items(): # Before the lifespan starts, "items" is still empty assert items == {} with TestClient(app) as client: # Inside the "with TestClient" block, the lifespan starts and items added assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} response = client.get("/items/foo") assert response.status_code == 200 assert response.json() == {"name": "Fighters"} # After the requests is done, the items are still there assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} # The end of the "with TestClient" block simulates terminating the app, so # the lifespan ends and items are cleaned up assert items == {}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/app_testing/tutorial004_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/async_tests/app_a_py310/main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Tomato"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/async_tests/app_a_py310/main.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/async_tests/app_a_py310/test_main.py
import pytest from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/async_tests/app_a_py310/test_main.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:docs_src/authentication_error_status_code/tutorial001_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer app = FastAPI() class HTTPBearer403(HTTPBearer): def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated" ) CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())] @app.get("/me") def read_me(credentials: CredentialsDep): return {"message": "You are authenticated", "token": credentials.credentials}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/authentication_error_status_code/tutorial001_an_py310.py", "license": "MIT License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/background_tasks/tutorial001_py310.py
from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="some notification") return {"message": "Notification sent in the background"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/background_tasks/tutorial001_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/behind_a_proxy/tutorial001_01_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/") def read_items(): return ["plumbus", "portal gun"]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/behind_a_proxy/tutorial001_01_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/behind_a_proxy/tutorial001_py310.py
from fastapi import FastAPI, Request app = FastAPI() @app.get("/app") def read_main(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/behind_a_proxy/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/behind_a_proxy/tutorial002_py310.py
from fastapi import FastAPI, Request app = FastAPI(root_path="/api/v1") @app.get("/app") def read_main(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/behind_a_proxy/tutorial002_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/behind_a_proxy/tutorial003_py310.py
from fastapi import FastAPI, Request app = FastAPI( servers=[ {"url": "https://stag.example.com", "description": "Staging environment"}, {"url": "https://prod.example.com", "description": "Production environment"}, ], root_path="/api/v1", ) @app.get("/app") def read_main(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/behind_a_proxy/tutorial003_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/behind_a_proxy/tutorial004_py310.py
from fastapi import FastAPI, Request app = FastAPI( servers=[ {"url": "https://stag.example.com", "description": "Staging environment"}, {"url": "https://prod.example.com", "description": "Production environment"}, ], root_path="/api/v1", root_path_in_servers=False, ) @app.get("/app") def read_main(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/behind_a_proxy/tutorial004_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/bigger_applications/app_an_py310/dependencies.py
from typing import Annotated from fastapi import Header, HTTPException async def get_token_header(x_token: Annotated[str, Header()]): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def get_query_token(token: str): if token != "jessica": raise HTTPException(status_code=400, detail="No Jessica token provided")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/bigger_applications/app_an_py310/dependencies.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/bigger_applications/app_an_py310/main.py
from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) app.include_router(items.router) app.include_router( admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(get_token_header)], responses={418: {"description": "I'm a teapot"}}, ) @app.get("/") async def root(): return {"message": "Hello Bigger Applications!"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/bigger_applications/app_an_py310/main.py", "license": "MIT License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/body_nested_models/tutorial008_py310.py
from fastapi import FastAPI from pydantic import BaseModel, HttpUrl app = FastAPI() class Image(BaseModel): url: HttpUrl name: str @app.post("/images/multiple/") async def create_multiple_images(images: list[Image]): return images
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/body_nested_models/tutorial008_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/body_nested_models/tutorial009_py310.py
from fastapi import FastAPI app = FastAPI() @app.post("/index-weights/") async def create_index_weights(weights: dict[int, float]): return weights
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/body_nested_models/tutorial009_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/conditional_openapi/tutorial001_py310.py
from fastapi import FastAPI from pydantic_settings import BaseSettings class Settings(BaseSettings): openapi_url: str = "/openapi.json" settings = Settings() app = FastAPI(openapi_url=settings.openapi_url) @app.get("/") def root(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/conditional_openapi/tutorial001_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/configure_swagger_ui/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI(swagger_ui_parameters={"syntaxHighlight": False}) @app.get("/users/{username}") async def read_user(username: str): return {"message": f"Hello {username}"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/configure_swagger_ui/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/configure_swagger_ui/tutorial002_py310.py
from fastapi import FastAPI app = FastAPI(swagger_ui_parameters={"syntaxHighlight": {"theme": "obsidian"}}) @app.get("/users/{username}") async def read_user(username: str): return {"message": f"Hello {username}"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/configure_swagger_ui/tutorial002_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/configure_swagger_ui/tutorial003_py310.py
from fastapi import FastAPI app = FastAPI(swagger_ui_parameters={"deepLinking": False}) @app.get("/users/{username}") async def read_user(username: str): return {"message": f"Hello {username}"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/configure_swagger_ui/tutorial003_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/cors/tutorial001_py310.py
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") async def main(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/cors/tutorial001_py310.py", "license": "MIT License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_docs_ui/tutorial001_py310.py
from fastapi import FastAPI from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) app = FastAPI(docs_url=None, redoc_url=None) @app.get("/docs", include_in_schema=False) async def custom_swagger_ui_html(): return get_swagger_ui_html( openapi_url=app.openapi_url, title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css", ) @app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False) async def swagger_ui_redirect(): return get_swagger_ui_oauth2_redirect_html() @app.get("/redoc", include_in_schema=False) async def redoc_html(): return get_redoc_html( openapi_url=app.openapi_url, title=app.title + " - ReDoc", redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js", ) @app.get("/users/{username}") async def read_user(username: str): return {"message": f"Hello {username}"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_docs_ui/tutorial001_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_docs_ui/tutorial002_py310.py
from fastapi import FastAPI from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) from fastapi.staticfiles import StaticFiles app = FastAPI(docs_url=None, redoc_url=None) app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/docs", include_in_schema=False) async def custom_swagger_ui_html(): return get_swagger_ui_html( openapi_url=app.openapi_url, title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, swagger_js_url="/static/swagger-ui-bundle.js", swagger_css_url="/static/swagger-ui.css", ) @app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False) async def swagger_ui_redirect(): return get_swagger_ui_oauth2_redirect_html() @app.get("/redoc", include_in_schema=False) async def redoc_html(): return get_redoc_html( openapi_url=app.openapi_url, title=app.title + " - ReDoc", redoc_js_url="/static/redoc.standalone.js", ) @app.get("/users/{username}") async def read_user(username: str): return {"message": f"Hello {username}"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_docs_ui/tutorial002_py310.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial001_py310.py
from fastapi import FastAPI from fastapi.responses import UJSONResponse app = FastAPI() @app.get("/items/", response_class=UJSONResponse) async def read_items(): return [{"item_id": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial001_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial001b_py310.py
from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI() @app.get("/items/", response_class=ORJSONResponse) async def read_items(): return ORJSONResponse([{"item_id": "Foo"}])
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial001b_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial002_py310.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/items/", response_class=HTMLResponse) async def read_items(): return """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial002_py310.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/custom_response/tutorial003_py310.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/items/") async def read_items(): html_content = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """ return HTMLResponse(content=html_content, status_code=200)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial003_py310.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/custom_response/tutorial004_py310.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() def generate_html_response(): html_content = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """ return HTMLResponse(content=html_content, status_code=200) @app.get("/items/", response_class=HTMLResponse) async def read_items(): return generate_html_response()
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial004_py310.py", "license": "MIT License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/custom_response/tutorial005_py310.py
from fastapi import FastAPI from fastapi.responses import PlainTextResponse app = FastAPI() @app.get("/", response_class=PlainTextResponse) async def main(): return "Hello World"
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial005_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial006_py310.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/typer") async def redirect_typer(): return RedirectResponse("https://typer.tiangolo.com")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial006_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial006b_py310.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/fastapi", response_class=RedirectResponse) async def redirect_fastapi(): return "https://fastapi.tiangolo.com"
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial006b_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial006c_py310.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/pydantic", response_class=RedirectResponse, status_code=302) async def redirect_pydantic(): return "https://docs.pydantic.dev/"
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial006c_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial007_py310.py
import anyio from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() async def fake_video_streamer(): for i in range(10): yield b"some fake video bytes" await anyio.sleep(0) @app.get("/") async def main(): return StreamingResponse(fake_video_streamer())
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial007_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial008_py310.py
from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") def main(): def iterfile(): # (1) with open(some_file_path, mode="rb") as file_like: # (2) yield from file_like # (3) return StreamingResponse(iterfile(), media_type="video/mp4")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial008_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial009_py310.py
from fastapi import FastAPI from fastapi.responses import FileResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") async def main(): return FileResponse(some_file_path)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial009_py310.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial009b_py310.py
from fastapi import FastAPI from fastapi.responses import FileResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/", response_class=FileResponse) async def main(): return some_file_path
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial009b_py310.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial009c_py310.py
from typing import Any import orjson from fastapi import FastAPI, Response app = FastAPI() class CustomORJSONResponse(Response): media_type = "application/json" def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed" return orjson.dumps(content, option=orjson.OPT_INDENT_2) @app.get("/", response_class=CustomORJSONResponse) async def main(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial009c_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/custom_response/tutorial010_py310.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI(default_response_class=HTMLResponse) @app.get("/items/") async def read_items(): return "<h1>Items</h1><p>This is a list of items.</p>"
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/custom_response/tutorial010_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/debugging/tutorial001_py310.py
import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): a = "a" b = "b" + a return {"hello world": b} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/debugging/tutorial001_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial006_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI, Header, HTTPException app = FastAPI() async def verify_token(x_token: Annotated[str, Header()]): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def verify_key(x_key: Annotated[str, Header()]): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key @app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)]) async def read_items(): return [{"item": "Foo"}, {"item": "Bar"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial006_an_py310.py", "license": "MIT License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial006_py310.py
from fastapi import Depends, FastAPI, Header, HTTPException app = FastAPI() async def verify_token(x_token: str = Header()): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def verify_key(x_key: str = Header()): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key @app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)]) async def read_items(): return [{"item": "Foo"}, {"item": "Bar"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial006_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008_an_py310.py
from typing import Annotated from fastapi import Depends async def dependency_a(): dep_a = generate_dep_a() try: yield dep_a finally: dep_a.close() async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]): dep_b = generate_dep_b() try: yield dep_b finally: dep_b.close(dep_a) async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]): dep_c = generate_dep_c() try: yield dep_c finally: dep_c.close(dep_b)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008_an_py310.py", "license": "MIT License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008_py310.py
from fastapi import Depends async def dependency_a(): dep_a = generate_dep_a() try: yield dep_a finally: dep_a.close() async def dependency_b(dep_a=Depends(dependency_a)): dep_b = generate_dep_b() try: yield dep_b finally: dep_b.close(dep_a) async def dependency_c(dep_b=Depends(dependency_b)): dep_c = generate_dep_c() try: yield dep_c finally: dep_c.close(dep_b)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008_py310.py", "license": "MIT License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008b_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI, HTTPException app = FastAPI() data = { "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, } class OwnerError(Exception): pass def get_username(): try: yield "Rick" except OwnerError as e: raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): if item_id not in data: raise HTTPException(status_code=404, detail="Item not found") item = data[item_id] if item["owner"] != username: raise OwnerError(username) return item
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008b_an_py310.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008b_py310.py
from fastapi import Depends, FastAPI, HTTPException app = FastAPI() data = { "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, } class OwnerError(Exception): pass def get_username(): try: yield "Rick" except OwnerError as e: raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") def get_item(item_id: str, username: str = Depends(get_username)): if item_id not in data: raise HTTPException(status_code=404, detail="Item not found") item = data[item_id] if item["owner"] != username: raise OwnerError(username) return item
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008b_py310.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008c_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI, HTTPException app = FastAPI() class InternalError(Exception): pass def get_username(): try: yield "Rick" except InternalError: print("Oops, we didn't raise again, Britney 😱") @app.get("/items/{item_id}") def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): if item_id == "portal-gun": raise InternalError( f"The portal gun is too dangerous to be owned by {username}" ) if item_id != "plumbus": raise HTTPException( status_code=404, detail="Item not found, there's only a plumbus here" ) return item_id
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008c_an_py310.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008c_py310.py
from fastapi import Depends, FastAPI, HTTPException app = FastAPI() class InternalError(Exception): pass def get_username(): try: yield "Rick" except InternalError: print("Oops, we didn't raise again, Britney 😱") @app.get("/items/{item_id}") def get_item(item_id: str, username: str = Depends(get_username)): if item_id == "portal-gun": raise InternalError( f"The portal gun is too dangerous to be owned by {username}" ) if item_id != "plumbus": raise HTTPException( status_code=404, detail="Item not found, there's only a plumbus here" ) return item_id
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008c_py310.py", "license": "MIT License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008d_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI, HTTPException app = FastAPI() class InternalError(Exception): pass def get_username(): try: yield "Rick" except InternalError: print("We don't swallow the internal error here, we raise again 😎") raise @app.get("/items/{item_id}") def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): if item_id == "portal-gun": raise InternalError( f"The portal gun is too dangerous to be owned by {username}" ) if item_id != "plumbus": raise HTTPException( status_code=404, detail="Item not found, there's only a plumbus here" ) return item_id
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008d_an_py310.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008d_py310.py
from fastapi import Depends, FastAPI, HTTPException app = FastAPI() class InternalError(Exception): pass def get_username(): try: yield "Rick" except InternalError: print("We don't swallow the internal error here, we raise again 😎") raise @app.get("/items/{item_id}") def get_item(item_id: str, username: str = Depends(get_username)): if item_id == "portal-gun": raise InternalError( f"The portal gun is too dangerous to be owned by {username}" ) if item_id != "plumbus": raise HTTPException( status_code=404, detail="Item not found, there's only a plumbus here" ) return item_id
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008d_py310.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008e_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() def get_username(): try: yield "Rick" finally: print("Cleanup up before response is sent") @app.get("/users/me") def get_user_me(username: Annotated[str, Depends(get_username, scope="function")]): return username
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008e_an_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial008e_py310.py
from fastapi import Depends, FastAPI app = FastAPI() def get_username(): try: yield "Rick" finally: print("Cleanup up before response is sent") @app.get("/users/me") def get_user_me(username: str = Depends(get_username, scope="function")): return username
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial008e_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial010_py310.py
class MySuperContextManager: def __init__(self): self.db = DBSession() def __enter__(self): return self.db def __exit__(self, exc_type, exc_value, traceback): self.db.close() async def get_db(): with MySuperContextManager() as db: yield db
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial010_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial011_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() class FixedContentQueryChecker: def __init__(self, fixed_content: str): self.fixed_content = fixed_content def __call__(self, q: str = ""): if q: return self.fixed_content in q return False checker = FixedContentQueryChecker("bar") @app.get("/query-checker/") async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]): return {"fixed_content_in_query": fixed_content_included}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial011_an_py310.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial011_py310.py
from fastapi import Depends, FastAPI app = FastAPI() class FixedContentQueryChecker: def __init__(self, fixed_content: str): self.fixed_content = fixed_content def __call__(self, q: str = ""): if q: return self.fixed_content in q return False checker = FixedContentQueryChecker("bar") @app.get("/query-checker/") async def read_query_check(fixed_content_included: bool = Depends(checker)): return {"fixed_content_in_query": fixed_content_included}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial011_py310.py", "license": "MIT License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial012_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI, Header, HTTPException async def verify_token(x_token: Annotated[str, Header()]): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def verify_key(x_key: Annotated[str, Header()]): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)]) @app.get("/items/") async def read_items(): return [{"item": "Portal Gun"}, {"item": "Plumbus"}] @app.get("/users/") async def read_users(): return [{"username": "Rick"}, {"username": "Morty"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial012_an_py310.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/dependencies/tutorial012_py310.py
from fastapi import Depends, FastAPI, Header, HTTPException async def verify_token(x_token: str = Header()): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def verify_key(x_key: str = Header()): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)]) @app.get("/items/") async def read_items(): return [{"item": "Portal Gun"}, {"item": "Plumbus"}] @app.get("/users/") async def read_users(): return [{"username": "Rick"}, {"username": "Morty"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/dependencies/tutorial012_py310.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/events/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() items = {} @app.on_event("startup") async def startup_event(): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"} @app.get("/items/{item_id}") async def read_items(item_id: str): return items[item_id]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/events/tutorial001_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/events/tutorial002_py310.py
from fastapi import FastAPI app = FastAPI() @app.on_event("shutdown") def shutdown_event(): with open("log.txt", mode="a") as log: log.write("Application shutdown") @app.get("/items/") async def read_items(): return [{"name": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/events/tutorial002_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/events/tutorial003_py310.py
from contextlib import asynccontextmanager from fastapi import FastAPI def fake_answer_to_everything_ml_model(x: float): return x * 42 ml_models = {} @asynccontextmanager async def lifespan(app: FastAPI): # Load the ML model ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model yield # Clean up the ML models and release the resources ml_models.clear() app = FastAPI(lifespan=lifespan) @app.get("/predict") async def predict(x: float): result = ml_models["answer_to_everything"](x) return {"result": result}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/events/tutorial003_py310.py", "license": "MIT License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/extending_openapi/tutorial001_py310.py
from fastapi import FastAPI from fastapi.openapi.utils import get_openapi app = FastAPI() @app.get("/items/") async def read_items(): return [{"name": "Foo"}] def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Custom title", version="2.5.0", summary="This is a very custom OpenAPI schema", description="Here's a longer description of the custom **OpenAPI** schema", routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" } app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = custom_openapi
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/extending_openapi/tutorial001_py310.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/extra_models/tutorial004_py310.py
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str items = [ {"name": "Foo", "description": "There comes my hero"}, {"name": "Red", "description": "It's my aeroplane"}, ] @app.get("/items/", response_model=list[Item]) async def read_items(): return items
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/extra_models/tutorial004_py310.py", "license": "MIT License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/extra_models/tutorial005_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/keyword-weights/", response_model=dict[str, float]) async def read_keyword_weights(): return {"foo": 2.3, "bar": 3.4}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/extra_models/tutorial005_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/first_steps/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/first_steps/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/first_steps/tutorial003_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/first_steps/tutorial003_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/generate_clients/tutorial004_py310.py
import json from pathlib import Path file_path = Path("./openapi.json") openapi_content = json.loads(file_path.read_text()) for path_data in openapi_content["paths"].values(): for operation in path_data.values(): tag = operation["tags"][0] operation_id = operation["operationId"] to_remove = f"{tag}-" new_operation_id = operation_id[len(to_remove) :] operation["operationId"] = new_operation_id file_path.write_text(json.dumps(openapi_content))
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/generate_clients/tutorial004_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/graphql_/tutorial001_py310.py
import strawberry from fastapi import FastAPI from strawberry.fastapi import GraphQLRouter @strawberry.type class User: name: str age: int @strawberry.type class Query: @strawberry.field def user(self) -> User: return User(name="Patrick", age=100) schema = strawberry.Schema(query=Query) graphql_app = GraphQLRouter(schema) app = FastAPI() app.include_router(graphql_app, prefix="/graphql")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/graphql_/tutorial001_py310.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/handling_errors/tutorial001_py310.py
from fastapi import FastAPI, HTTPException app = FastAPI() items = {"foo": "The Foo Wrestlers"} @app.get("/items/{item_id}") async def read_item(item_id: str): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return {"item": items[item_id]}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/handling_errors/tutorial001_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/handling_errors/tutorial002_py310.py
from fastapi import FastAPI, HTTPException app = FastAPI() items = {"foo": "The Foo Wrestlers"} @app.get("/items-header/{item_id}") async def read_item_header(item_id: str): if item_id not in items: raise HTTPException( status_code=404, detail="Item not found", headers={"X-Error": "There goes my error"}, ) return {"item": items[item_id]}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/handling_errors/tutorial002_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/handling_errors/tutorial003_py310.py
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse class UnicornException(Exception): def __init__(self, name: str): self.name = name app = FastAPI() @app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException): return JSONResponse( status_code=418, content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, ) @app.get("/unicorns/{name}") async def read_unicorn(name: str): if name == "yolo": raise UnicornException(name=name) return {"unicorn_name": name}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/handling_errors/tutorial003_py310.py", "license": "MIT License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/handling_errors/tutorial004_py310.py
from fastapi import FastAPI, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.responses import PlainTextResponse from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request, exc): return PlainTextResponse(str(exc.detail), status_code=exc.status_code) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc: RequestValidationError): message = "Validation errors:" for error in exc.errors(): message += f"\nField: {error['loc']}, Error: {error['msg']}" return PlainTextResponse(message, status_code=400) @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 3: raise HTTPException(status_code=418, detail="Nope! I don't like 3.") return {"item_id": item_id}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/handling_errors/tutorial004_py310.py", "license": "MIT License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/handling_errors/tutorial005_py310.py
from fastapi import FastAPI, Request from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel app = FastAPI() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}), ) class Item(BaseModel): title: str size: int @app.post("/items/") async def create_item(item: Item): return item
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/handling_errors/tutorial005_py310.py", "license": "MIT License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/handling_errors/tutorial006_py310.py
from fastapi import FastAPI, HTTPException from fastapi.exception_handlers import ( http_exception_handler, request_validation_exception_handler, ) from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() @app.exception_handler(StarletteHTTPException) async def custom_http_exception_handler(request, exc): print(f"OMG! An HTTP error!: {repr(exc)}") return await http_exception_handler(request, exc) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc): print(f"OMG! The client sent invalid data!: {exc}") return await request_validation_exception_handler(request, exc) @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 3: raise HTTPException(status_code=418, detail="Nope! I don't like 3.") return {"item_id": item_id}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/handling_errors/tutorial006_py310.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/metadata/tutorial001_1_py310.py
from fastapi import FastAPI description = """ ChimichangApp API helps you do awesome stuff. 🚀 ## Items You can **read items**. ## Users You will be able to: * **Create users** (_not implemented_). * **Read users** (_not implemented_). """ app = FastAPI( title="ChimichangApp", description=description, summary="Deadpool's favorite app. Nuff said.", version="0.0.1", terms_of_service="http://example.com/terms/", contact={ "name": "Deadpoolio the Amazing", "url": "http://x-force.example.com/contact/", "email": "dp@x-force.example.com", }, license_info={ "name": "Apache 2.0", "identifier": "Apache-2.0", }, ) @app.get("/items/") async def read_items(): return [{"name": "Katana"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/metadata/tutorial001_1_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/metadata/tutorial001_py310.py
from fastapi import FastAPI description = """ ChimichangApp API helps you do awesome stuff. 🚀 ## Items You can **read items**. ## Users You will be able to: * **Create users** (_not implemented_). * **Read users** (_not implemented_). """ app = FastAPI( title="ChimichangApp", description=description, summary="Deadpool's favorite app. Nuff said.", version="0.0.1", terms_of_service="http://example.com/terms/", contact={ "name": "Deadpoolio the Amazing", "url": "http://x-force.example.com/contact/", "email": "dp@x-force.example.com", }, license_info={ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html", }, ) @app.get("/items/") async def read_items(): return [{"name": "Katana"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/metadata/tutorial001_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/metadata/tutorial002_py310.py
from fastapi import FastAPI app = FastAPI(openapi_url="/api/v1/openapi.json") @app.get("/items/") async def read_items(): return [{"name": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/metadata/tutorial002_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/metadata/tutorial003_py310.py
from fastapi import FastAPI app = FastAPI(docs_url="/documentation", redoc_url=None) @app.get("/items/") async def read_items(): return [{"name": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/metadata/tutorial003_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/metadata/tutorial004_py310.py
from fastapi import FastAPI tags_metadata = [ { "name": "users", "description": "Operations with users. The **login** logic is also here.", }, { "name": "items", "description": "Manage items. So _fancy_ they have their own docs.", "externalDocs": { "description": "Items external docs", "url": "https://fastapi.tiangolo.com/", }, }, ] app = FastAPI(openapi_tags=tags_metadata) @app.get("/users/", tags=["users"]) async def get_users(): return [{"name": "Harry"}, {"name": "Ron"}] @app.get("/items/", tags=["items"]) async def get_items(): return [{"name": "wand"}, {"name": "flying broom"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/metadata/tutorial004_py310.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/middleware/tutorial001_py310.py
import time from fastapi import FastAPI, Request app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.perf_counter() response = await call_next(request) process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/middleware/tutorial001_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/openapi_webhooks/tutorial001_py310.py
from datetime import datetime from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Subscription(BaseModel): username: str monthly_fee: float start_date: datetime @app.webhooks.post("new-subscription") def new_subscription(body: Subscription): """ When a new user subscribes to your service we'll send you a POST request with this data to the URL that you register for the event `new-subscription` in the dashboard. """ @app.get("/users/") def read_users(): return ["Rick", "Morty"]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/openapi_webhooks/tutorial001_py310.py", "license": "MIT License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_operation_advanced_configuration/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/", operation_id="some_specific_id_you_define") async def read_items(): return [{"item_id": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_advanced_configuration/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_operation_advanced_configuration/tutorial002_py310.py
from fastapi import FastAPI from fastapi.routing import APIRoute app = FastAPI() @app.get("/items/") async def read_items(): return [{"item_id": "Foo"}] def use_route_names_as_operation_ids(app: FastAPI) -> None: """ Simplify operation IDs so that generated API clients have simpler function names. Should be called only after all routes have been added. """ for route in app.routes: if isinstance(route, APIRoute): route.operation_id = route.name # in this case, 'read_items' use_route_names_as_operation_ids(app)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_advanced_configuration/tutorial002_py310.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_operation_advanced_configuration/tutorial003_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/", include_in_schema=False) async def read_items(): return [{"item_id": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_advanced_configuration/tutorial003_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple