prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
ions.abc import AsyncIterable from typing import Annotated from fastapi import FastAPI, Header from fastapi.sse import EventSourceResponse, ServerSentEvent from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float items = [ Item(name="Plumbus", price=32.99), Item...
ne, Header()] = None, ) -> AsyncIterable[ServerSentEvent]: start = last_event_id + 1 if last_event_id is not None else 0 for i, item in enumerate(items): if i < start: continue yield ServerSentEvent(data=item, id=str(i))
tated[int | No
{ "filepath": "docs_src/server_sent_events/tutorial004_py310.py", "language": "python", "file_size": 795, "cut_index": 524, "middle_length": 14 }
dFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files( files: Annotated[list[bytes], File(description="Multiple files as bytes")], ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( fil...
ctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </f
: content = """ <body> <form action="/files/" en
{ "filepath": "docs_src/request_files/tutorial003_an_py310.py", "language": "python", "file_size": 952, "cut_index": 582, "middle_length": 52 }
app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Annotated[ Item, Body( examples=[ { ...
"35.4", }, { "name": "Baz", "price": "thirty five point four", }, ], ), ], ): results = {"item_id": item_id, "item": item} return resul
"name": "Bar", "price":
{ "filepath": "docs_src/schema_extra_example/tutorial004_an_py310.py", "language": "python", "file_size": 917, "cut_index": 606, "middle_length": 52 }
typing import Annotated from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files(files: Annotated[list[bytes], File()]): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_...
" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
ltipart/form-data" method="post"> <input name="files
{ "filepath": "docs_src/request_files/tutorial002_an_py310.py", "language": "python", "file_size": 826, "cut_index": 517, "middle_length": 52 }
ted from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) age: int | None = Field(default=None, index=True) ...
tAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/") def create_hero(hero: Hero, session: SessionDep) -> Hero: session.add(hero) session.commit() session.refresh(hero) return hero @app.get
nnect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] app = Fas
{ "filepath": "docs_src/sql_databases/tutorial001_an_py310.py", "language": "python", "file_size": 1768, "cut_index": 537, "middle_length": 229 }
FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.136.3" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile from .e...
from .param_functions import Query as Query from .param_functions import Security as Security from .requests import Request as Request from .responses import Response as Response from .routing import APIRouter as APIRouter from .websockets import WebSocket
s Cookie from .param_functions import Depends as Depends from .param_functions import File as File from .param_functions import Form as Form from .param_functions import Header as Header from .param_functions import Path as Path
{ "filepath": "fastapi/__init__.py", "language": "python", "file_size": 1081, "cut_index": 515, "middle_length": 229 }
vent schema matching the OpenAPI 3.2 spec # (Section 4.14.4 "Special Considerations for Server-Sent Events") _SSE_EVENT_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "data": {"type": "string"}, "event": {"type": "string"}, "id": {"type": "string"}, "retry": {"type"...
`POST`. The actual encoding logic lives in the FastAPI routing layer. This class serves mainly as a marker and sets the correct `Content-Type`. """ media_type = "text/event-stream" def _check_single_line(v: str | None, field_name: str)
nse` on a *path operation* that uses `yield` to enable Server Sent Events (SSE) responses. Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible with protocols like MCP that stream SSE over
{ "filepath": "fastapi/sse.py", "language": "python", "file_size": 6848, "cut_index": 716, "middle_length": 229 }
shot from pydantic import BaseModel app = FastAPI() class Items(BaseModel): items: dict[str, int] @app.post("/foo") def foo(items: Items): return items.items client = TestClient(app) def test_additional_properties_post(): response = client.post("/foo", json={"items": {"foo": 1, "bar": 2}}) asse...
"post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}},
tus_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/foo": {
{ "filepath": "tests/test_additional_properties.py", "language": "python", "file_size": 4238, "cut_index": 614, "middle_length": 229 }
ontextlib 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...
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
ty 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"}}
{ "filepath": "docs_src/app_testing/tutorial004_py310.py", "language": "python", "file_size": 1187, "cut_index": 518, "middle_length": 229 }
mport TestClient from .main import app client = TestClient(app) def test_read_item(): response = client.get("/items/foo", headers={"X-Token": "coneofsilence"}) assert response.status_code == 200 assert response.json() == { "id": "foo", "title": "Foo", "description": "There goes m...
: "Item not found"} def test_create_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"}, ) assert response.status
{"detail": "Invalid X-Token header"} def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail"
{ "filepath": "docs_src/app_testing/app_b_py310/test_main.py", "language": "python", "file_size": 1866, "cut_index": 537, "middle_length": 229 }
yping import Annotated from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, } app = F...
not found") return fake_db[item_id] @app.post("/items/") async def create_item(item: Item, x_token: Annotated[str, Header()]) -> Item: if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header")
nnotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item
{ "filepath": "docs_src/app_testing/app_b_an_py310/main.py", "language": "python", "file_size": 1163, "cut_index": 518, "middle_length": 229 }
astapi 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_...
r_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/
ger-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_swagge
{ "filepath": "docs_src/custom_docs_ui/tutorial001_py310.py", "language": "python", "file_size": 1143, "cut_index": 518, "middle_length": 229 }
m fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, } app = FastAPI() class Item(BaseM...
id] @app.post("/items/") async def create_item(item: Item, x_token: str = Header()) -> Item: if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPE
ken != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_
{ "filepath": "docs_src/app_testing/app_b_py310/main.py", "language": "python", "file_size": 1113, "cut_index": 515, "middle_length": 229 }
mport TestClient from .main import app client = TestClient(app) def test_read_item(): response = client.get("/items/foo", headers={"X-Token": "coneofsilence"}) assert response.status_code == 200 assert response.json() == { "id": "foo", "title": "Foo", "description": "There goes m...
: "Item not found"} def test_create_item(): response = client.post( "/items/", headers={"X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"}, ) assert response.status
{"detail": "Invalid X-Token header"} def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail"
{ "filepath": "docs_src/app_testing/app_b_an_py310/test_main.py", "language": "python", "file_size": 1866, "cut_index": 537, "middle_length": 229 }
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, sum...
le.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 [{"nam
/x-force.examp
{ "filepath": "docs_src/metadata/tutorial001_py310.py", "language": "python", "file_size": 805, "cut_index": 517, "middle_length": 14 }
pi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float = 10.5 items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2...
response_model_include=["name", "description"], ) async def read_item_name(item_id: str): return items[item_id] @app.get("/items/{item_id}/public", response_model=Item, response_model_exclude=["tax"]) async def read_item_public_data(item_id: str):
del=Item,
{ "filepath": "docs_src/response_model/tutorial006_py310.py", "language": "python", "file_size": 816, "cut_index": 522, "middle_length": 14 }
l def custom_generate_unique_id(route: APIRoute): return f"{route.tags[0]}-{route.name}" app = FastAPI(generate_unique_id_function=custom_generate_unique_id) class Item(BaseModel): name: str price: float class ResponseMessage(BaseModel): message: str class User(BaseModel): username: str ...
): return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ] @app.post("/users/", response_model=ResponseMessage, tags=["users"]) async def create_user(user: User): return {"message": "User received"}
del=list[Item], tags=["items"]) async def get_items(
{ "filepath": "docs_src/generate_clients/tutorial003_py310.py", "language": "python", "file_size": 914, "cut_index": 606, "middle_length": 52 }
from fastapi import APIRouter, Depends, HTTPException from ..dependencies import get_token_header router = APIRouter( prefix="/items", tags=["items"], dependencies=[Depends(get_token_header)], responses={404: {"description": "Not found"}}, ) fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"...
"Operation forbidden"}}, ) async def update_item(item_id: str): if item_id != "plumbus": raise HTTPException( status_code=403, detail="You can only update the item: plumbus" ) return {"item_id": item_id, "name": "The gr
raise HTTPException(status_code=404, detail="Item not found") return {"name": fake_items_db[item_id]["name"], "item_id": item_id} @router.put( "/{item_id}", tags=["custom"], responses={403: {"description":
{ "filepath": "docs_src/bigger_applications/app_an_py310/routers/items.py", "language": "python", "file_size": 1011, "cut_index": 512, "middle_length": 229 }
dantic import BaseModel, EmailStr app = FastAPI() class UserIn(BaseModel): username: str password: str email: EmailStr full_name: str | None = None class UserOut(BaseModel): username: str email: EmailStr full_name: str | None = None class UserInDB(BaseModel): username: str has...
_in.password) user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password) print("User saved! ..not really") return user_in_db @app.post("/user/", response_model=UserOut) async def create_user(user_in: UserIn): user_save
In): hashed_password = fake_password_hasher(user
{ "filepath": "docs_src/extra_models/tutorial001_py310.py", "language": "python", "file_size": 905, "cut_index": 547, "middle_length": 52 }
fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class UserBase(BaseModel): username: str email: EmailStr full_name: str | None = None class UserIn(UserBase): password: str class UserOut(UserBase): pass class UserInDB(UserBase): hashed_password: str def ...
(**user_in.model_dump(), hashed_password=hashed_password) print("User saved! ..not really") return user_in_db @app.post("/user/", response_model=UserOut) async def create_user(user_in: UserIn): user_saved = fake_save_user(user_in) return
_db = UserInDB
{ "filepath": "docs_src/extra_models/tutorial002_py310.py", "language": "python", "file_size": 798, "cut_index": 517, "middle_length": 14 }
FastAPI, Query, WebSocket, WebSocketException, status, ) from fastapi.responses import HTMLResponse app = FastAPI() html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <form action="" onsubmit="sendMessage(event)"> ...
form> <ul id='messages'> </ul> <script> var ws = null; function connect(event) { var itemId = document.getElementById("itemId") var token = document.getElementById("token")
n"/></label> <button onclick="connect(event)">Connect</button> <hr> <label>Message: <input type="text" id="messageText" autocomplete="off"/></label> <button>Send</button> </
{ "filepath": "docs_src/websockets_/tutorial002_py310.py", "language": "python", "file_size": 2798, "cut_index": 563, "middle_length": 229 }
sconnect from fastapi.responses import HTMLResponse app = FastAPI() html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <h2>Your ID: <span id="ws-id"></span></h2> <form action="" onsubmit="sendMessage(event)"> <inp...
document.getElementById('messages') var message = document.createElement('li') var content = document.createTextNode(event.data) message.appendChild(content) messages.appendChild(message)
e.now() document.querySelector("#ws-id").textContent = client_id; var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`); ws.onmessage = function(event) { var messages =
{ "filepath": "docs_src/websockets_/tutorial003_py310.py", "language": "python", "file_size": 2549, "cut_index": 563, "middle_length": 229 }
import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return {...
response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_items_with_q(): response = c
client = TestClient(app) async def override_dependency(q: str | None = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependency def test_override_in_items():
{ "filepath": "docs_src/dependency_testing/tutorial001_py310.py", "language": "python", "file_size": 1478, "cut_index": 524, "middle_length": 229 }
astapi 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("/do...
se) 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"
_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=Fal
{ "filepath": "docs_src/custom_docs_ui/tutorial002_py310.py", "language": "python", "file_size": 1175, "cut_index": 518, "middle_length": 229 }
import FastAPI, WebSocket from fastapi.responses import HTMLResponse app = FastAPI() html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <form action="" onsubmit="sendMessage(event)"> <input type="text" id="messageText" a...
data) message.appendChild(content) messages.appendChild(message) }; function sendMessage(event) { var input = document.getElementById("messageText") ws.send(input.value
ws.onmessage = function(event) { var messages = document.getElementById('messages') var message = document.createElement('li') var content = document.createTextNode(event.
{ "filepath": "docs_src/websockets_/tutorial001_py310.py", "language": "python", "file_size": 1432, "cut_index": 524, "middle_length": 229 }
atetime import datetime, time, timedelta from typing import Annotated from uuid import UUID from fastapi import Body, FastAPI app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, start_datetime: Annotated[datetime, Body()], end_datetime: Annotated[datetime, Body()], proc...
"item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, "process_after": process_after, "repeat_at": repeat_at, "start_process": start_process, "duration": duration, }
return {
{ "filepath": "docs_src/extra_data_types/tutorial001_an_py310.py", "language": "python", "file_size": 788, "cut_index": 518, "middle_length": 14 }
dantic 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 da...
n": 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)
= body.data.decode("utf-8") return {"descriptio
{ "filepath": "docs_src/json_base64_bytes/tutorial001_py310.py", "language": "python", "file_size": 892, "cut_index": 547, "middle_length": 52 }
Cookie, Depends, FastAPI, Query, WebSocket, WebSocketException, status, ) from fastapi.responses import HTMLResponse app = FastAPI() html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <form action="" onsu...
utton>Send</button> </form> <ul id='messages'> </ul> <script> var ws = null; function connect(event) { var itemId = document.getElementById("itemId") var token = document.g
ete="off" value="some-key-token"/></label> <button onclick="connect(event)">Connect</button> <hr> <label>Message: <input type="text" id="messageText" autocomplete="off"/></label> <b
{ "filepath": "docs_src/websockets_/tutorial002_an_py310.py", "language": "python", "file_size": 2855, "cut_index": 563, "middle_length": 229 }
ted from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_...
y def test_override_in_items(): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_overrid
: "Hello Users!", "params": commons} client = TestClient(app) async def override_dependency(q: str | None = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependenc
{ "filepath": "docs_src/dependency_testing/tutorial001_an_py310.py", "language": "python", "file_size": 1528, "cut_index": 537, "middle_length": 229 }
epends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class HeroBase(SQLModel): name: str = Field(index=True) age: int | None = Field(default=None, index=True) class Hero(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True) ...
def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] app = FastAPI() @app.on_event("startup") def on_s
None secret_name: str | None = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args)
{ "filepath": "docs_src/sql_databases/tutorial002_an_py310.py", "language": "python", "file_size": 2567, "cut_index": 563, "middle_length": 229 }
, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class HeroBase(SQLModel): name: str = Field(index=True) age: int | None = Field(default=None, index=True) class Hero(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True) secret_name: str class Her...
SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroPubl
ne = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables():
{ "filepath": "docs_src/sql_databases/tutorial002_py310.py", "language": "python", "file_size": 2586, "cut_index": 563, "middle_length": 229 }
from fastapi.responses import StreamingResponse from sqlmodel import Field, Session, SQLModel, create_engine engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db") class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str app = FastAPI() def...
s_code=403, detail="Not authorized") def generate_stream(query: str): for ch in query: yield ch time.sleep(0.1) @app.get("/generate", dependencies=[Depends(get_user)]) def generate(query: str): return StreamingResponse(content=g
) if not user: raise HTTPException(statu
{ "filepath": "docs_src/dependencies/tutorial013_an_py310.py", "language": "python", "file_size": 937, "cut_index": 606, "middle_length": 52 }
import APIRouter, FastAPI from pydantic import BaseModel, HttpUrl app = FastAPI() class Invoice(BaseModel): id: str title: str | None = None customer: str total: float class InvoiceEvent(BaseModel): description: str paid: bool class InvoiceEventReceived(BaseModel): ok: bool invoice...
he API user (some external developer) create an invoice. And this path operation will: * Send the invoice to the client. * Collect the money from the client. * Send a notification back to the API user (the external developer), as a ca
eEvent): pass @app.post("/invoices/", callbacks=invoices_callback_router.routes) def create_invoice(invoice: Invoice, callback_url: HttpUrl | None = None): """ Create an invoice. This will (let's imagine) let t
{ "filepath": "docs_src/openapi_callbacks/tutorial001_py310.py", "language": "python", "file_size": 1333, "cut_index": 524, "middle_length": 229 }
gAAAB0AAAAdCAYAAABWk2cPAAAAbnpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjadYzRDYAwCET/mcIRDoq0jGOiJm7g+NJK0vjhS4DjIEfHfZ20DKqSrrWZmyFQV5ctRMOLACxglNCcXk7zVqFzJzF8kV6R5vOJ97yVH78HjfYAtg0ged033ZgAAAoCaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zO...
dpZHRoPSIyOSIKICAgdGlmZjpJbWFnZUxlbmd0aD0iMjkiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiLz4KIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgIC
3V0PSIiCiAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyIKICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIgogICBleGlmOlBpeGVsWERpbWVuc2lvbj0iMjkiCiAgIGV4aWY6UGl4ZWxZRGltZW5zaW9uPSIyOSIKICAgdGlmZjpJbWFnZV
{ "filepath": "docs_src/stream_data/tutorial002_py310.py", "language": "python", "file_size": 5717, "cut_index": 716, "middle_length": 229 }
rt FastAPI from fastapi.encoders import jsonable_encoder from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str | None = None description: str | None = None price: float | None = None tax: float = 10.5 tags: list[str] = [] items = { "foo": {"name": "Foo", "price": 5...
f read_item(item_id: str): return items[item_id] @app.put("/items/{item_id}", response_model=Item) async def update_item(item_id: str, item: Item): update_item_encoded = jsonable_encoder(item) items[item_id] = update_item_encoded return u
et("/items/{item_id}", response_model=Item) async de
{ "filepath": "docs_src/body_updates/tutorial001_py310.py", "language": "python", "file_size": 856, "cut_index": 529, "middle_length": 52 }
ds, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) age: int | None = Field(default=None, index=True) secret_name: str sqlite_file...
.post("/heroes/") def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: session.add(hero) session.commit() session.refresh(hero) return hero @app.get("/heroes/") def read_heroes( session: Session = Depends(get_
d_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app
{ "filepath": "docs_src/sql_databases/tutorial001_py310.py", "language": "python", "file_size": 1760, "cut_index": 537, "middle_length": 229 }
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() message = """ Rick: (stumbles in drunkenly, and turns on the lights) Morty! You gotta come on. You got--... you gotta come with me. Morty: (rubs his eyes) What, Rick? What's going on? Rick: I got a surprise for you, Morty. ...
sync def stream_story() -> AsyncIterable[str]: for line in message.splitlines(): yield line @app.get("/story/stream-no-async", response_class=StreamingResponse) def stream_story_no_async() -> Iterable[str]: for line in message.splitlines(
orty out of his bed and into the hall) Morty: Ow! Ow! You're tugging me too hard! Rick: We gotta go, gotta get outta here, come on. Got a surprise for you Morty. """ @app.get("/story/stream", response_class=StreamingResponse) a
{ "filepath": "docs_src/stream_data/tutorial001_py310.py", "language": "python", "file_size": 2243, "cut_index": 563, "middle_length": 229 }
FastAPI, HTTPException from fastapi.responses import StreamingResponse from sqlmodel import Field, Session, SQLModel, create_engine engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db") class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str...
aise HTTPException(status_code=403, detail="Not authorized") session.close() def generate_stream(query: str): for ch in query: yield ch time.sleep(0.1) @app.get("/generate", dependencies=[Depends(get_user)]) def generate(query:
ession.get(User, user_id) if not user: r
{ "filepath": "docs_src/dependencies/tutorial014_an_py310.py", "language": "python", "file_size": 957, "cut_index": 582, "middle_length": 52 }
sses import field # (1) from fastapi import FastAPI from pydantic.dataclasses import dataclass # (2) @dataclass class Item: name: str description: str | None = None @dataclass class Author: name: str items: list[Item] = field(default_factory=list) # (3) app = FastAPI() @app.post("/authors/{a...
"description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies"}, ], }, { "name": "System of an Up", "items": [ {
hors/", response_model=list[Author]) # (7) def get_authors(): # (8) return [ # (9) { "name": "Breaters", "items": [ { "name": "Island In The Moon",
{ "filepath": "docs_src/dataclasses_/tutorial003_py310.py", "language": "python", "file_size": 1363, "cut_index": 524, "middle_length": 229 }
rt Callable from typing import Annotated, Any from annotated_doc import Doc from starlette.background import BackgroundTasks as StarletteBackgroundTasks from typing_extensions import ParamSpec P = ParamSpec("P") class BackgroundTasks(StarletteBackgroundTasks): """ A collection of background tasks that will ...
"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,
## Example ```python from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f
{ "filepath": "fastapi/background.py", "language": "python", "file_size": 1820, "cut_index": 537, "middle_length": 229 }
rom starlette.datastructures import URL as URL # noqa: F401 from starlette.datastructures import Address as Address # noqa: F401 from starlette.datastructures import FormData as FormData # noqa: F401 from starlette.datastructures import Headers as Headers # noqa: F401 from starlette.datastructures import QueryParam...
to access the raw standard Python file (blocking, not async), useful and needed for non-async code. Read more about it in the [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). ## Example ```pytho
etteUploadFile): """ A file uploaded in a request. Define it as a *path operation function* (or dependency) parameter. If you are using a regular `def` function, you can use the `upload_file.file` attribute
{ "filepath": "fastapi/datastructures.py", "language": "python", "file_size": 5321, "cut_index": 716, "middle_length": 229 }
otated, Any from uuid import UUID from annotated_doc import Doc from fastapi.exceptions import PydanticV1NotSupportedError from fastapi.types import IncEx from pydantic import BaseModel from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr from pydantic_core import PydanticU...
dantic_extra_types.color import Color as PyExtraColor except ImportError: # pragma: no cover class PyExtraColor: # type: ignore[no-redef] pass # Taken from Pydantic v1 as is def isoformat(o: datetime.date | datetime.time) -> str: retur
color import Color # ty: ignore[deprecated] except ImportError: # pragma: no cover class Color: # type: ignore[no-redef] pass try: # Supporting the new Color format for newer versions of Pydantic from py
{ "filepath": "fastapi/encoders.py", "language": "python", "file_size": 11603, "cut_index": 921, "middle_length": 229 }
Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeri...
-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less t
Less than. If set, value must be less than this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path
{ "filepath": "fastapi/param_functions.py", "language": "python", "file_size": 69596, "cut_index": 3790, "middle_length": 229 }
annotation: Any | None = None, alias: str | None = None, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt:...
= None, discriminator: str | None = None, strict: bool | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None =
None, pattern: str | None = None, regex: Annotated[ str | None, deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ]
{ "filepath": "fastapi/params.py", "language": "python", "file_size": 26205, "cut_index": 1331, "middle_length": 229 }
from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str | None = None description: str | None = None price: float | None = None tax: float = 10.5 tags: list[str] = [] items = { "foo": {"name": ...
ata = items[item_id] stored_item_model = Item(**stored_item_data) update_data = item.model_dump(exclude_unset=True) updated_item = stored_item_model.model_copy(update=update_data) items[item_id] = jsonable_encoder(updated_item) return u
: []}, } @app.get("/items/{item_id}", response_model=Item) async def read_item(item_id: str): return items[item_id] @app.patch("/items/{item_id}") async def update_item(item_id: str, item: Item) -> Item: stored_item_d
{ "filepath": "docs_src/body_updates/tutorial002_py310.py", "language": "python", "file_size": 1009, "cut_index": 512, "middle_length": 229 }
ions.abc import AsyncGenerator from contextlib import AbstractContextManager from contextlib import asynccontextmanager as asynccontextmanager from typing import TypeVar import anyio.to_thread from anyio import CapacityLimiter from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa fro...
tions/deadlocks if the context manager itself # has its own internal pool (e.g. a database connection pool) # to avoid this we let __exit__ run without a capacity limit # since we're creating a new limiter for each call, any non-zero limit
Var("_T") @asynccontextmanager async def contextmanager_in_threadpool( cm: AbstractContextManager[_T], ) -> AsyncGenerator[_T, None]: # blocking __exit__ from running waiting on a free thread # can create race condi
{ "filepath": "fastapi/concurrency.py", "language": "python", "file_size": 1489, "cut_index": 524, "middle_length": 229 }
Exception as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException class EndpointContext(TypedDict, total=False): function: str path: str file: str line: int class HTTPException(StarletteHTTPException): """ An HTTP exception you can raise i...
tlers"} @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]} ``` """ def __
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). ## Example ```python from fastapi import FastAPI, HTTPException app = FastAPI() items = {"foo": "The Foo Wres
{ "filepath": "fastapi/exceptions.py", "language": "python", "file_size": 7453, "cut_index": 716, "middle_length": 229 }
tManager[Any]: return _AsyncLiftContextManager(cmgr(app)) return wrapper def _merge_lifespan_context( original_context: Lifespan[Any], nested_context: Lifespan[Any] ) -> Lifespan[Any]: @asynccontextmanager async def merged_lifespan( app: AppType, ) -> AsyncIterator[Mapping[str, An...
# type: ignore[return-value] # ty: ignore[invalid-return-type] class _DefaultLifespan: """ Default lifespan context manager that runs on_startup and on_shutdown handlers. This is a copy of the Starlette _DefaultLifespan class that was remov
d maybe_original_state is None: yield None # old ASGI compatibility else: yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} return merged_lifespan
{ "filepath": "fastapi/routing.py", "language": "python", "file_size": 197568, "cut_index": 7068, "middle_length": 229 }
ult automatic endpoints `/docs` and `/redoc` will also be disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). **Example** ```python from fasta...
* `@app.get("/users/", tags=["users"])` * `@app.get("/items/", tags=["items"])` The order of the tags can be used to specify the order shown in tools like Swagger UI, used in the automatic path `/d
nnotated[ list[dict[str, Any]] | None, Doc( """ A list of tags used by OpenAPI, these are the same `tags` you can set in the *path operations*, like:
{ "filepath": "fastapi/applications.py", "language": "python", "file_size": 181285, "cut_index": 7068, "middle_length": 229 }
tionWarning from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa from starlette.responses import FileResponse as FileResponse # noqa from starlette.responses import HTMLResponse as HTMLResponse # noqa from starlette.responses import JSONResponse as JSONResponse # noqa from starlette.responses i...
ss _OrjsonModule(Protocol): OPT_NON_STR_KEYS: int OPT_SERIALIZE_NUMPY: int def dumps(self, __obj: Any, *, option: int = ...) -> bytes: ... try: ujson = cast(_UjsonModule, importlib.import_module("ujson")) except ModuleNotFoundError: # p
rom starlette.responses import StreamingResponse as StreamingResponse # noqa from typing_extensions import deprecated class _UjsonModule(Protocol): def dumps(self, __obj: Any, *, ensure_ascii: bool = ...) -> str: ... cla
{ "filepath": "fastapi/responses.py", "language": "python", "file_size": 4144, "cut_index": 614, "middle_length": 229 }
.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import is_body_allowed_for_status_code from fastapi.websockets import WebSocket from starlette.exceptions import HTTPException from starlette.requests import Request from starlette...
ode=exc.status_code, headers=headers ) async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=422, content={"detail": jsonable_encoder(
= getattr(exc, "headers", None) if not is_body_allowed_for_status_code(exc.status_code): return Response(status_code=exc.status_code, headers=headers) return JSONResponse( {"detail": exc.detail}, status_c
{ "filepath": "fastapi/exception_handlers.py", "language": "python", "file_size": 1275, "cut_index": 524, "middle_length": 229 }
api from fastapi._compat import ( ModelField, PydanticSchemaGenerationError, Undefined, annotation_is_pydantic_v1, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError from pydantic.fields import FieldI...
"4XX", "5XX", }: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> set[str]: return set(re.finda
_code is None: return True # Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1 if status_code in { "default", "1XX", "2XX", "3XX",
{ "filepath": "fastapi/utils.py", "language": "python", "file_size": 4341, "cut_index": 614, "middle_length": 229 }
ie from .api_key import APIKeyHeader as APIKeyHeader from .api_key import APIKeyQuery as APIKeyQuery from .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials from .http import HTTPBasic as HTTPBasic from .http import HTTPBasicCredentials as HTTPBasicCredentials from .http import HTTPBearer as HTTP...
th2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestForm from .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrict from .oauth2 import SecurityScopes as SecurityScopes from .open_id_connect_url import OpenIdConnect as
uth2PasswordBearer as OAuth2PasswordBearer from .oau
{ "filepath": "fastapi/security/__init__.py", "language": "python", "file_size": 881, "cut_index": 559, "middle_length": 52 }
BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class HTTPBasicCredentials(BaseModel): """ The HTTP Basic credentials given as the result of using `HTTPBasic` in a dependency. Read more about it in the [FastAPI docs for HTTP Basic Auth](https:/...
st space. The first part is the `scheme`, the second part is the `credentials`. For example, in an HTTP Bearer token scheme, the client will send a header like: ``` Authorization: Bearer deadbeef12346 ``` In this case:
class HTTPAuthorizationCredentials(BaseModel): """ The HTTP authorization credentials in the result of using `HTTPBearer` or `HTTPDigest` in a dependency. The HTTP authorization header value is split by the fir
{ "filepath": "fastapi/security/http.py", "language": "python", "file_size": 13410, "cut_index": 921, "middle_length": 229 }
ds `username` and `password`. All the initialization parameters are extracted from the request. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). ## Example ```python from typing import Annotate...
ata.client_id if form_data.client_secret: data["client_secret"] = form_data.client_secret return data ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. You could have custom inte
asswordRequestForm, Depends()]): data = {} data["scopes"] = [] for scope in form_data.scopes: data["scopes"].append(scope) if form_data.client_id: data["client_id"] = form_d
{ "filepath": "fastapi/security/oauth2.py", "language": "python", "file_size": 24178, "cut_index": 1331, "middle_length": 229 }
TypeGuard, TypeVar, Union, get_args, get_origin, ) from fastapi.types import UnionType from pydantic import BaseModel from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile _T = TypeVar("_T") # Copy from Pydantic: pydantic/_internal/_typing_extra.py ...
et: frozenset, deque: deque, } sequence_types: tuple[type[Any], ...] = tuple(sequence_annotation_to_type.keys()) # Copy of Pydantic: pydantic/_internal/_utils.py with added TypeGuard def lenient_issubclass( cls: Any, class_or_tuple: type[_T] | t
[reportAttributeAccessIssue] PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) sequence_annotation_to_type = { Sequence: list, list: list, tuple: tuple, set: set, frozens
{ "filepath": "fastapi/_compat/shared.py", "language": "python", "file_size": 7118, "cut_index": 716, "middle_length": 229 }
.replace("<", "\\u003c") .replace(">", "\\u003e") .replace("&", "\\u0026") ) swagger_ui_default_parameters: Annotated[ dict[str, Any], Doc( """ Default configurations for Swagger UI. You can use it as a template to add any other configurations needed. ...
`/openapi.json`. Read more about it in the [FastAPI docs for Conditional OpenAPI](https://fastapi.tiangolo.com/how-to/conditional-openapi/#conditional-openapi-from-settings-and-env-vars) """ ), ], t
*, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that Swagger UI should load and use. This is normally done automatically by FastAPI using the default URL
{ "filepath": "fastapi/openapi/docs.py", "language": "python", "file_size": 12425, "cut_index": 921, "middle_length": 229 }
API from fastapi.params import Body, ParamTypes from fastapi.responses import Response from fastapi.sse import _SSE_EVENT_SCHEMA from fastapi.types import ModelNameMap from fastapi.utils import ( deep_dict_update, generate_operation_id_for_path, is_body_allowed_for_status_code, ) from pydantic import BaseMo...
"type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, "required": ["loc", "msg", "type"], } validation_error_response_definition = { "title": "HTTPV
: { "loc": { "title": "Location", "type": "array", "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, }, "msg": {"title": "Message", "type": "string"},
{ "filepath": "fastapi/openapi/utils.py", "language": "python", "file_size": 26240, "cut_index": 1331, "middle_length": 229 }
port BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import ( FormData, Headers, ImmutableMultiDict, QueryParams, UploadFile, ) from starlette.requests import HTTPConnection, Request from starlette.responses import Respons...
led "multipart" instead. \n' 'You can remove "multipart" with: \n\n' "pip uninstall multipart\n\n" 'And then install "python-multipart" with: \n\n' "pip install python-multipart\n" ) def ensure_multipart_is_installed() -> None: try:
nstalled. \n' 'You can install "python-multipart" with: \n\n' "pip install python-multipart\n" ) multipart_incorrect_install_error = ( 'Form data requires "python-multipart" to be installed. ' 'It seems you instal
{ "filepath": "fastapi/dependencies/utils.py", "language": "python", "file_size": 39728, "cut_index": 2151, "middle_length": 229 }
name: str, description: str | None, scheme_name: str | None, auto_error: bool, ): self.auto_error = auto_error self.model: APIKey = APIKey( **{"in": location}, # ty: ignore[invalid-argument-type] name=name, description=description...
0#name-401-unauthorized For this, this method sends a custom challenge `APIKey`. """ return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticat
ot standardized for API Key authentication but the HTTP specification requires that an error of 401 "Unauthorized" must include a WWW-Authenticate header. Ref: https://datatracker.ietf.org/doc/html/rfc911
{ "filepath": "fastapi/security/api_key.py", "language": "python", "file_size": 9793, "cut_index": 921, "middle_length": 229 }
PYDANTIC_VERSION_MINOR_TUPLE from .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1 from .shared import field_annotation_is_scalar as field_annotation_is_scalar from .shared import ( field_annotation_is_scalar_sequence as field_annotation_is_scalar_sequence, ) from .shared import field_annotati...
oadfile_annotation, ) from .shared import ( is_uploadfile_sequence_annotation as is_uploadfile_sequence_annotation, ) from .shared import lenient_issubclass as lenient_issubclass from .shared import sequence_types as sequence_types from .shared import
nnotation as is_bytes_sequence_annotation from .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance from .shared import ( is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_upl
{ "filepath": "fastapi/_compat/__init__.py", "language": "python", "file_size": 2095, "cut_index": 563, "middle_length": 229 }
typing_deprecated try: import email_validator assert email_validator # make autoflake ignore the unused import from pydantic import EmailStr except ImportError: # pragma: no cover class EmailStr(str): # type: ignore[no-redef] @classmethod def __get_validators__(cls) -> Iterable[Cal...
logger.warning( "email-validator not installed, email fields will be treated as str.\n" "To install, run: pip install email-validator" ) return str(__input_value) @classmethod
il fields will be treated as str.\n" "To install, run: pip install email-validator" ) return str(v) @classmethod def _validate(cls, __input_value: Any, _: Any) -> str:
{ "filepath": "fastapi/openapi/models.py", "language": "python", "file_size": 14608, "cut_index": 921, "middle_length": 229 }
API documentation.", "url": "https://docs.example.com/api-general", } app = FastAPI(openapi_external_docs=external_docs) @app.api_route("/api_route") def non_operation(): return {"message": "Hello World"} def non_decorated_route(): return {"message": "Hello World"} app.add_api_route("/non_decorated_r...
get("/path/bool/{item_id}") def get_bool_id(item_id: bool): return item_id @app.get("/path/param/{item_id}") def get_path_param_id(item_id: str | None = Path()): return item_id @app.get("/path/param-minlength/{item_id}") def get_path_param_min_
def get_str_id(item_id: str): return item_id @app.get("/path/int/{item_id}") def get_int_id(item_id: int): return item_id @app.get("/path/float/{item_id}") def get_float_id(item_id: float): return item_id @app.
{ "filepath": "tests/main.py", "language": "python", "file_size": 4558, "cut_index": 614, "middle_length": 229 }
onnect as OpenIdConnectModel from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class OpenIdConnect(SecurityBase): """ OpenID Connect authentication class. An instance of it wou...
c( """ The OpenID Connect URL. """ ), ], scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will
, it doesn't use the OpenIDConnect URL. You would need to subclass it and implement it in your code. """ def __init__( self, *, openIdConnectUrl: Annotated[ str, Do
{ "filepath": "fastapi/security/open_id_connect_url.py", "language": "python", "file_size": 3136, "cut_index": 614, "middle_length": 229 }
import ModelField from fastapi.security.base import SecurityBase from fastapi.types import DependencyCacheKey if sys.version_info >= (3, 13): # pragma: no cover from inspect import iscoroutinefunction else: # pragma: no cover from asyncio import iscoroutinefunction def _unwrapped_call(call: Callable[..., ...
ld] = field(default_factory=list) header_params: list[ModelField] = field(default_factory=list) cookie_params: list[ModelField] = field(default_factory=list) body_params: list[ModelField] = field(default_factory=list) dependencies: list["De
]) -> Callable[..., Any]: while isinstance(func, partial): func = func.func return func @dataclass class Dependant: path_params: list[ModelField] = field(default_factory=list) query_params: list[ModelFie
{ "filepath": "fastapi/dependencies/models.py", "language": "python", "file_size": 7250, "cut_index": 716, "middle_length": 229 }
ping_extra from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] GetJsonSchemaHandler as GetJsonSchemaHandler, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema from pydantic.json_schema import JsonSchem...
= None, localns: dict[str, Any] | None = None, ) -> Any: # eval_type_lenient has been deprecated since Pydantic v2.10.0b1 (PR #10530) try_eval_type = getattr(_pydantic_typing_extra, "try_eval_type", None) if try_eval_type is not None:
ort ( with_info_plain_validator_function as with_info_plain_validator_function, ) RequiredParam = PydanticUndefined Undefined = PydanticUndefined def evaluate_forwardref( value: Any, globalns: dict[str, Any] | None
{ "filepath": "fastapi/_compat/v2.py", "language": "python", "file_size": 17601, "cut_index": 1331, "middle_length": 229 }
rt Awaitable, Callable from contextvars import ContextVar from typing import Any from fastapi import Depends, FastAPI, Request, Response from fastapi.testclient import TestClient legacy_request_state_context_var: ContextVar[dict[str, Any] | None] = ContextVar( "legacy_request_state_context_var", default=None ) a...
next(request) response.headers["custom"] = "foo" return response @app.get("/user", dependencies=[Depends(set_up_request_state_dependency)]) def get_user(): request_state = legacy_request_state_context_var.get() assert request_state re
est_state legacy_request_state_context_var.reset(contextvar_token) @app.middleware("http") async def custom_middleware( request: Request, call_next: Callable[[Request], Awaitable[Response]] ): response = await call_
{ "filepath": "tests/test_dependency_contextvars.py", "language": "python", "file_size": 1568, "cut_index": 537, "middle_length": 229 }
subprocess import sys from unittest.mock import patch import fastapi.cli import pytest def test_fastapi_cli(): result = subprocess.run( [ sys.executable, "-m", "coverage", "run", "-m", "fastapi", "dev", "non_e...
e.py" in result.stdout def test_fastapi_cli_not_installed(): with patch.object(fastapi.cli, "cli_main", None): with pytest.raises(RuntimeError) as exc_info: fastapi.cli.main() assert "To use the fastapi command, please ins
out assert "Path does not exist non_existent_fil
{ "filepath": "tests/test_fastapi_cli.py", "language": "python", "file_size": 866, "cut_index": 529, "middle_length": 52 }
shot from pydantic import BaseModel, ConfigDict class FooBaseModel(BaseModel): model_config = ConfigDict(extra="forbid") class Foo(FooBaseModel): pass app = FastAPI() @app.post("/") async def post( foo: Foo | None = None, ): return foo client = TestClient(app) def test_call_invalid(): re...
"openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post", "operationId": "post__post",
== 200 assert response.json() == {} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( {
{ "filepath": "tests/test_additional_properties_bool.py", "language": "python", "file_size": 4351, "cut_index": 614, "middle_length": 229 }
import APIRouter, FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot router = APIRouter() sub_router = APIRouter() app = FastAPI() @sub_router.get("/") def read_item(): return {"id": "foo"} router.include_router(sub_router, prefix="/items") app.include_router(router) cl...
e": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Resp
test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"titl
{ "filepath": "tests/test_additional_response_extra.py", "language": "python", "file_size": 1336, "cut_index": 524, "middle_length": 229 }
class CustomModel(BaseModel): a: int app = FastAPI() callback_router = APIRouter(default_response_class=JSONResponse) @callback_router.get( "{$callback_url}/callback/", responses={400: {"model": CustomModel}} ) def callback_route(): pass # pragma: no cover @app.post("/", callbacks=callback_router.r...
"post": { "summary": "Main Route", "operationId": "main_route__post", "parameters": [ { "required": True,
e.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": {
{ "filepath": "tests/test_additional_responses_custom_model_in_callback.py", "language": "python", "file_size": 6028, "cut_index": 716, "middle_length": 229 }
TestClient from inline_snapshot import snapshot from pydantic import BaseModel app = FastAPI() class JsonApiResponse(JSONResponse): media_type = "application/vnd.api+json" class Error(BaseModel): status: str title: str class JsonApiError(BaseModel): errors: list[Error] @app.get( "/a/{id}", ...
astAPI", "version": "0.1.0"}, "paths": { "/a/{id}": { "get": { "responses": { "422": { "description": "Error",
openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "F
{ "filepath": "tests/test_additional_responses_custom_validationerror.py", "language": "python", "file_size": 3253, "cut_index": 614, "middle_length": 229 }
p = FastAPI() router = APIRouter() @router.get("/a", responses={501: {"description": "Error 1"}}) async def a(): return "a" @router.get( "/b", responses={ 502: {"description": "Error 2"}, "4XX": {"description": "Error with range, upper"}, }, ) async def b(): return "b" @router....
) async def d(): return "d" app.include_router(router) client = TestClient(app) def test_a(): response = client.get("/a") assert response.status_code == 200, response.text assert response.json() == "a" def test_b(): response = c
se"}, }, ) async def c(): return "c" @router.get( "/d", responses={ "400": {"description": "Error with str"}, "5XX": {"model": ResponseModel}, "default": {"model": ResponseModel}, },
{ "filepath": "tests/test_additional_responses_router.py", "language": "python", "file_size": 5704, "cut_index": 716, "middle_length": 229 }
e duplicate $ref entries in anyOf arrays. See https://github.com/fastapi/fastapi/pull/14463 """ from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot from pydantic import BaseModel class ModelA(BaseModel): a: str class ModelB(BaseModel): b: str app = F...
) assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/route1": {
("/route1") async def route1(): pass # pragma: no cover @app.get("/route2") async def route2(): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json"
{ "filepath": "tests/test_additional_responses_union_duplicate_anyof.py", "language": "python", "file_size": 4405, "cut_index": 614, "middle_length": 229 }
t("/multiple") async def multiple(foo: Annotated[str, object(), Query(min_length=1)]): return {"foo": foo} @app.get("/unrelated") async def unrelated(foo: Annotated[str, object()]): return {"foo": foo} client = TestClient(app) foo_is_missing = { "detail": [ { "loc": ["query", "foo"]...
ted_status,expected_response", [ ("/default", 200, {"foo": "foo"}), ("/default?foo=bar", 200, {"foo": "bar"}), ("/required?foo=bar", 200, {"foo": "bar"}), ("/required", 422, foo_is_missing), ("/required?foo=", 42
1}, "loc": ["query", "foo"], "msg": "String should have at least 1 character", "type": "string_too_short", "input": "", } ] } @pytest.mark.parametrize( "path,expec
{ "filepath": "tests/test_annotated.py", "language": "python", "file_size": 10725, "cut_index": 921, "middle_length": 229 }
TestClient from inline_snapshot import snapshot @pytest.fixture(name="client") def get_client(): from pydantic import ( BaseModel, ConfigDict, PlainSerializer, TypeAdapter, WithJsonSchema, ) class FakeNumpyArray: def __init__(self): self.data =...
del(custom_field=FakeNumpyArray()) client = TestClient(app) return client def test_get(client: TestClient): response = client.get("/") assert response.json() == {"custom_field": [1.0, 2.0, 3.0]} def test_typeadapter(): # This test
] class MyModel(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) custom_field: FakeNumpyArrayPydantic app = FastAPI() @app.get("/") def test() -> MyModel: return MyMo
{ "filepath": "tests/test_arbitrary_types.py", "language": "python", "file_size": 3886, "cut_index": 614, "middle_length": 229 }
"foo bar" def test_openapi_schema(): 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"}, "externalDocs": { ...
n": {"schema": {}}}, } }, "summary": "Non Operation", "operationId": "non_operation_api_route_get", } },
"get": { "responses": { "200": { "description": "Successful Response", "content": {"application/jso
{ "filepath": "tests/test_application.py", "language": "python", "file_size": 58296, "cut_index": 2151, "middle_length": 229 }
shot app = FastAPI() @app.get("/a/{id}") async def a(id): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1...
"schema": { "$ref": "#/components/schemas/HTTPValidationError" } } },
"422": { "description": "Validation Error", "content": { "application/json": {
{ "filepath": "tests/test_additional_responses_default_validationerror.py", "language": "python", "file_size": 3409, "cut_index": 614, "middle_length": 229 }
ted import pytest from fastapi import Body, FastAPI, Query from fastapi.testclient import TestClient app = FastAPI() @app.post("/") async def get( x: Annotated[float, Query(allow_inf_nan=True)] = 0, y: Annotated[float, Query(allow_inf_nan=False)] = 0, z: Annotated[float, Query()] = 0, b: Annotated[f...
e, response.text @pytest.mark.parametrize( "value,code", [ ("-1", 200), ("inf", 422), ("-inf", 422), ("nan", 422), ("0", 200), ("342", 200), ], ) def test_allow_inf_nan_param_false(value: str, c
("-inf", 200), ("nan", 200), ("0", 200), ("342", 200), ], ) def test_allow_inf_nan_param_true(value: str, code: int): response = client.post(f"/?x={value}") assert response.status_code == cod
{ "filepath": "tests/test_allow_inf_nan_in_enforcing.py", "language": "python", "file_size": 1823, "cut_index": 537, "middle_length": 229 }
stapi import Depends, FastAPI, Path from fastapi.param_functions import Query from fastapi.testclient import TestClient app = FastAPI() def test_no_annotated_defaults(): with pytest.raises( AssertionError, match="Path parameters cannot have a default value" ): @app.get("/items/{item_id}/") ...
pass # pragma: nocover def test_multiple_annotations(): async def dep(): pass # pragma: nocover @app.get("/multi-query") async def get(foo: Annotated[int, Query(gt=2), Query(lt=10)]): return foo with pytest.raises(
efault value cannot be set in `Annotated` for 'item_id'. Set the" " default value with `=` instead." ), ): @app.get("/") async def get(item_id: Annotated[int, Query(default=1)]):
{ "filepath": "tests/test_ambiguous_params.py", "language": "python", "file_size": 2072, "cut_index": 563, "middle_length": 229 }
TestClient from inline_snapshot import snapshot from pydantic import BaseModel app = FastAPI() class JsonApiResponse(JSONResponse): media_type = "application/vnd.api+json" class Error(BaseModel): status: str title: str class JsonApiError(BaseModel): errors: list[Error] @app.get( "/a", r...
assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { "get": { "responses":
n": "Error", "model": Error}}) async def b(): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text
{ "filepath": "tests/test_additional_responses_response_class.py", "language": "python", "file_size": 3887, "cut_index": 614, "middle_length": 229 }
ort pytest from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get("/a", responses={"hello": {"description": "Not a valid additional response"}}) async def a(): pass # pragma: no cover openapi_schema = { "openapi": "3.1.0", "info": {"title": "FastAPI", "version":...
"Successful Response", "content": {"application/json": {"schema": {}}}, }, }, "summary": "A", "operationId": "a_a_get", } } }, } client =
but since the key is not valid, openapi.utils.get_openapi will raise ValueError "hello": {"description": "Not a valid additional response"}, "200": { "description":
{ "filepath": "tests/test_additional_responses_bad.py", "language": "python", "file_size": 1117, "cut_index": 515, "middle_length": 229 }
_sequence_annotation, ) from fastapi._compat.shared import is_bytes_sequence_annotation from fastapi.testclient import TestClient from pydantic import BaseModel, ConfigDict from pydantic.fields import FieldInfo def test_model_field_default_required(): from fastapi._compat import v2 # For coverage field_i...
onse2 = client.post("/", json=[1, 2]) assert response2.status_code == 200, response2.text assert response2.json() == [1, 2] def test_propagates_pydantic2_model_config(): app = FastAPI() class Missing: def __bool__(self):
def foo(foo: str | list[int]): return foo client = TestClient(app) response = client.post("/", json="bar") assert response.status_code == 200, response.text assert response.json() == "bar" resp
{ "filepath": "tests/test_compat.py", "language": "python", "file_size": 4326, "cut_index": 614, "middle_length": 229 }
ot import snapshot @pytest.fixture(name="client") def get_client(request): separate_input_output_schemas = request.param app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) from pydantic import BaseModel, computed_field class Rectangle(BaseModel): width: int le...
t @pytest.mark.parametrize("client", [True, False], indirect=True) @pytest.mark.parametrize("path", ["/", "/responses"]) def test_get(client: TestClient, path: str): response = client.get(path) assert response.status_code == 200, response.text
urn Rectangle(width=3, length=4) @app.get("/responses", responses={200: {"model": Rectangle}}) def read_responses() -> Rectangle: return Rectangle(width=3, length=4) client = TestClient(app) return clien
{ "filepath": "tests/test_computed_fields.py", "language": "python", "file_size": 3852, "cut_index": 614, "middle_length": 229 }
.testclient import TestClient from inline_snapshot import snapshot from starlette.routing import Route app = FastAPI() class APIRouteA(APIRoute): x_type = "A" class APIRouteB(APIRoute): x_type = "B" class APIRouteC(APIRoute): x_type = "C" router_a = APIRouter(route_class=APIRouteA) router_b = APIRo...
lient(app) @pytest.mark.parametrize( "path,expected_status,expected_response", [ ("/a", 200, {"msg": "A"}), ("/a/b", 200, {"msg": "B"}), ("/a/b/c", 200, {"msg": "C"}), ], ) def test_get_path(path, expected_status, expe
outer_c.get("/") def get_c(): return {"msg": "C"} router_b.include_router(router=router_c, prefix="/c") router_a.include_router(router=router_b, prefix="/b") app.include_router(router=router_a, prefix="/a") client = TestC
{ "filepath": "tests/test_custom_route_class.py", "language": "python", "file_size": 3356, "cut_index": 614, "middle_length": 229 }
import Annotated from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, WithJsonSchema app = FastAPI() class Item(BaseModel): name: str description: Annotated[str | None, WithJsonSchema({"type": ["string", "null"]})] = ( None ) model_config = ...
"type": "string", }, "description": { "title": "Description", "type": ["string", "null"], }, }, } def test_custom_response_schema(): response = client.get("/openapi.json") assert resp
TestClient(app) item_schema = { "title": "Item", "required": ["name"], "type": "object", "x-something-internal": { "level": 4, }, "properties": { "name": { "title": "Name",
{ "filepath": "tests/test_custom_schema_fields.py", "language": "python", "file_size": 1325, "cut_index": 524, "middle_length": 229 }
m fastapi import FastAPI from fastapi.testclient import TestClient swagger_ui_oauth2_redirect_url = "/docs/redirect" app = FastAPI(swagger_ui_oauth2_redirect_url=swagger_ui_oauth2_redirect_url) @app.get("/items/") async def read_items(): return {"id": "foo"} client = TestClient(app) def test_swagger_ui(): ...
e = client.get(swagger_ui_oauth2_redirect_url) assert response.status_code == 200, response.text assert response.headers["content-type"] == "text/html; charset=utf-8" assert "window.opener.swaggerUIRedirectOauth2" in response.text def test_re
n response.text print(client.base_url) assert ( f"oauth2RedirectUrl: window.location.origin + '{swagger_ui_oauth2_redirect_url}'" in response.text ) def test_swagger_ui_oauth2_redirect(): respons
{ "filepath": "tests/test_custom_swagger_ui_redirect.py", "language": "python", "file_size": 1091, "cut_index": 515, "middle_length": 229 }
t needs_orjson class ORJSONResponse(JSONResponse): media_type = "application/x-orjson" def render(self, content: Any) -> bytes: import orjson return orjson.dumps(content) class OverrideResponse(JSONResponse): media_type = "application/x-override" app = FastAPI(default_response_class=...
de(): return "Hello World" @router_a.get("/") def get_a(): return {"msg": "Hello A"} @router_a.get("/override", response_class=PlainTextResponse) def get_a_path_override(): return "Hello A" @router_a_a.get("/") def get_a_a(): return {
_a = APIRouter() router_b_a_c_override = APIRouter() # Overrides default class again @app.get("/") def get_root(): return {"msg": "Hello World"} @app.get("/override", response_class=PlainTextResponse) def get_path_overri
{ "filepath": "tests/test_default_response_class.py", "language": "python", "file_size": 5454, "cut_index": 716, "middle_length": 229 }
ted, Any import pytest from fastapi import Depends, FastAPI, HTTPException from fastapi.testclient import TestClient class CustomError(Exception): pass def catching_dep() -> Any: try: yield "s" except CustomError as err: raise HTTPException(status_code=418, detail="Session error") from ...
response = client.get("/catching") assert response.status_code == 418 assert response.json() == {"detail": "Session error"} def test_broken_raise(): with pytest.raises(ValueError, match="Broken after yield"): client.get("/broken")
raise CustomError("Simulated error during streaming") @app.get("/broken") def broken(d: Annotated[str, Depends(broken_dep)]) -> Any: return {"message": "all good?"} client = TestClient(app) def test_catching():
{ "filepath": "tests/test_dependency_after_yield_raise.py", "language": "python", "file_size": 1774, "cut_index": 537, "middle_length": 229 }
rt Generator from contextlib import contextmanager from typing import Annotated, Any import pytest from fastapi import Depends, FastAPI, WebSocket from fastapi.testclient import TestClient class Session: def __init__(self) -> None: self.data = ["foo", "bar", "baz"] self.open = True def __ite...
as s: yield s def broken_dep_session() -> Any: with acquire_session() as s: s.open = False yield s SessionDep = Annotated[Session, Depends(dep_session)] BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] app
) @contextmanager def acquire_session() -> Generator[Session, None, None]: session = Session() try: yield session finally: session.open = False def dep_session() -> Any: with acquire_session()
{ "filepath": "tests/test_dependency_after_yield_websockets.py", "language": "python", "file_size": 2005, "cut_index": 537, "middle_length": 229 }
fastapi.testclient import TestClient app = FastAPI() counter_holder = {"counter": 0} async def dep_counter(): counter_holder["counter"] += 1 return counter_holder["counter"] async def super_dep(count: int = Depends(dep_counter)): return count @app.get("/counter/") async def get_counter(count: int =...
n {"counter": count, "subcounter": subcount} @app.get("/scope-counter") async def get_scope_counter( count: int = Security(dep_counter), scope_count_1: int = Security(dep_counter, scopes=["scope"]), scope_count_2: int = Security(dep_counter,
turn {"counter": count, "subcounter": subcount} @app.get("/sub-counter-no-cache/") async def get_sub_counter_no_cache( subcount: int = Depends(super_dep), count: int = Depends(dep_counter, use_cache=False), ): retur
{ "filepath": "tests/test_dependency_cache.py", "language": "python", "file_size": 2787, "cut_index": 563, "middle_length": 229 }
uter, FastAPI, File, UploadFile from fastapi.exceptions import HTTPException from fastapi.testclient import TestClient app = FastAPI() router = APIRouter() class ContentSizeLimitMiddleware: """Content size limiting middleware for ASGI applications Args: app (ASGI application): ASGI application m...
essage["type"] != "http.request": return message # pragma: no cover body_len = len(message.get("body", b"")) received += body_len if received > self.max_content_size: raise HTTPException
= app self.max_content_size = max_content_size def receive_wrapper(self, receive): received = 0 async def inner(): nonlocal received message = await receive() if m
{ "filepath": "tests/test_custom_middleware_exception.py", "language": "python", "file_size": 2861, "cut_index": 563, "middle_length": 229 }
ime import datetime, timezone from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel def test_pydanticv2(): from pydantic import field_serializer class ModelWithDatetimeField(BaseModel): dt_field: datetime @field_serializer("dt_field") d...
(2019, 1, 1, 8)) @app.get("/model", response_model=ModelWithDatetimeField) def get_model(): return model client = TestClient(app) with client: response = client.get("/model") assert response.json() == {"dt_field": "201
field=datetime
{ "filepath": "tests/test_datetime_custom_encoder.py", "language": "python", "file_size": 817, "cut_index": 522, "middle_length": 14 }
ia_type = "application/x-override" app = FastAPI() router_a = APIRouter() router_a_a = APIRouter() router_a_b_override = APIRouter() # Overrides default class router_b_override = APIRouter() # Overrides default class router_b_a = APIRouter() router_b_a_c_override = APIRouter() # Overrides default class again @ap...
er_a_a.get("/override", response_class=PlainTextResponse) def get_a_a_path_override(): return "Hello A A" @router_a_b_override.get("/") def get_a_b(): return "Hello A B" @router_a_b_override.get("/override", response_class=HTMLResponse) def get
f get_a(): return {"msg": "Hello A"} @router_a.get("/override", response_class=PlainTextResponse) def get_a_path_override(): return "Hello A" @router_a_a.get("/") def get_a_a(): return {"msg": "Hello A A"} @rout
{ "filepath": "tests/test_default_response_class_router.py", "language": "python", "file_size": 5117, "cut_index": 716, "middle_length": 229 }
API from fastapi.testclient import TestClient app = FastAPI() class CallableDependency: def __call__(self, value: str) -> str: return value class CallableGenDependency: def __call__(self, value: str) -> Generator[str, None, None]: yield value class AsyncCallableDependency: async def _...
e]: yield value async def asynchronous_gen(self, value: str) -> AsyncGenerator[str, None]: yield value callable_dependency = CallableDependency() callable_gen_dependency = CallableGenDependency() async_callable_dependency = AsyncCall
thodsDependency: def synchronous(self, value: str) -> str: return value async def asynchronous(self, value: str) -> str: return value def synchronous_gen(self, value: str) -> Generator[str, None, Non
{ "filepath": "tests/test_dependency_class.py", "language": "python", "file_size": 4466, "cut_index": 614, "middle_length": 229 }
"context_b": "not started b", "bg": "not set", "sync_bg": "not set", } errors = [] async def get_state(): return state class AsyncDependencyError(Exception): pass class SyncDependencyError(Exception): pass class OtherDependencyError(Exception): pass async def asyncgen_state(state: ...
se"] = "asyncgen raise started" try: yield state["/async_raise"] except AsyncDependencyError: errors.append("/async_raise") raise finally: state["/async_raise"] = "asyncgen raise finalized" def generator_state_
= Depends(get_state)): state["/sync"] = "generator started" yield state["/sync"] state["/sync"] = "generator completed" async def asyncgen_state_try(state: dict[str, str] = Depends(get_state)): state["/async_rai
{ "filepath": "tests/test_dependency_contextmanager.py", "language": "python", "file_size": 11763, "cut_index": 921, "middle_length": 229 }
ed, Any import pytest from fastapi import Depends, FastAPI from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient class Session: def __init__(self) -> None: self.data = ["foo", "bar", "baz"] self.open = True def __iter__(self) -> Generator[str, None, None]:...
ession() -> Any: with acquire_session() as s: s.open = False yield s SessionDep = Annotated[Session, Depends(dep_session)] BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] app = FastAPI() @app.get("/data") def get
) -> Generator[Session, None, None]: session = Session() try: yield session finally: session.open = False def dep_session() -> Any: with acquire_session() as s: yield s def broken_dep_s
{ "filepath": "tests/test_dependency_after_yield_streaming.py", "language": "python", "file_size": 3312, "cut_index": 614, "middle_length": 229 }
port Path import pytest from fastapi import FastAPI, UploadFile from fastapi.datastructures import Default from fastapi.testclient import TestClient def test_upload_file_invalid_pydantic_v2(): with pytest.raises(ValueError): UploadFile._validate("not a Starlette UploadFile", {}) def test_default_placeh...
path.write_bytes(b"<file content>") app = FastAPI() testing_file_store: list[UploadFile] = [] @app.post("/uploadfile/") def create_upload_file(file: UploadFile): testing_file_store.append(file) return {"filename": file.f
ault_placeholder_bool(): placeholder_a = Default("a") placeholder_b = Default("") assert placeholder_a assert not placeholder_b def test_upload_file_is_closed(tmp_path: Path): path = tmp_path / "test.txt"
{ "filepath": "tests/test_datastructures.py", "language": "python", "file_size": 1830, "cut_index": 537, "middle_length": 229 }
aseModel): data: str def duplicate_dependency(item: Item): return item def dependency(item2: Item): return item2 def sub_duplicate_dependency( item: Item, sub_item: Item = Depends(duplicate_dependency) ): return [item, sub_item] @app.post("/with-duplicates") async def with_duplicates(item: I...
e = client.post("/no-duplicates", json={"item": {"data": "myitem"}}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body",
em, item2] @app.post("/with-duplicates-sub") async def no_duplicates_sub( item: Item, sub_items: list[Item] = Depends(sub_duplicate_dependency) ): return [item, sub_items] def test_no_duplicates_invalid(): respons
{ "filepath": "tests/test_dependency_duplicates.py", "language": "python", "file_size": 8993, "cut_index": 716, "middle_length": 229 }
astAPI, HTTPException, Security from fastapi.security import ( OAuth2PasswordBearer, SecurityScopes, ) from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def process_auth( credentials: Annotated[str | None, Security(oauth2_scheme)], secur...
scopes: raise HTTPException(detail="a or b not in scopes", status_code=401) return {"token": credentials, "scopes": security_scopes.scopes} @app.get("/get-credentials") def get_credentials( credentials: Annotated[dict, Security(process_au
test # here is just to check if FastAPI is indeed registering and passing the scopes # correctly when using Security with parameterless dependencies. if "a" not in security_scopes.scopes or "b" not in security_scopes.
{ "filepath": "tests/test_dependency_paramless.py", "language": "python", "file_size": 2370, "cut_index": 563, "middle_length": 229 }