Browse Source

🔥 Remove Python 3.9 specific files, no longer needed after updating translations (#14931)

pull/14932/head
Sebastián Ramírez 4 months ago
committed by GitHub
parent
commit
bbb96d4a0a
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 22
      docs_src/additional_responses/tutorial001_py39.py
  2. 37
      docs_src/additional_responses/tutorial003_py39.py
  3. 11
      docs_src/advanced_middleware/tutorial001_py39.py
  4. 13
      docs_src/advanced_middleware/tutorial002_py39.py
  5. 11
      docs_src/advanced_middleware/tutorial003_py39.py
  6. 0
      docs_src/app_testing/app_a_py39/__init__.py
  7. 8
      docs_src/app_testing/app_a_py39/main.py
  8. 11
      docs_src/app_testing/app_a_py39/test_main.py
  9. 18
      docs_src/app_testing/tutorial001_py39.py
  10. 31
      docs_src/app_testing/tutorial002_py39.py
  11. 24
      docs_src/app_testing/tutorial003_py39.py
  12. 43
      docs_src/app_testing/tutorial004_py39.py
  13. 0
      docs_src/async_tests/app_a_py39/__init__.py
  14. 8
      docs_src/async_tests/app_a_py39/main.py
  15. 14
      docs_src/async_tests/app_a_py39/test_main.py
  16. 21
      docs_src/authentication_error_status_code/tutorial001_an_py39.py
  17. 15
      docs_src/background_tasks/tutorial001_py39.py
  18. 8
      docs_src/behind_a_proxy/tutorial001_01_py39.py
  19. 8
      docs_src/behind_a_proxy/tutorial001_py39.py
  20. 8
      docs_src/behind_a_proxy/tutorial002_py39.py
  21. 14
      docs_src/behind_a_proxy/tutorial003_py39.py
  22. 15
      docs_src/behind_a_proxy/tutorial004_py39.py
  23. 0
      docs_src/bigger_applications/app_an_py39/__init__.py
  24. 13
      docs_src/bigger_applications/app_an_py39/dependencies.py
  25. 0
      docs_src/bigger_applications/app_an_py39/internal/__init__.py
  26. 8
      docs_src/bigger_applications/app_an_py39/internal/admin.py
  27. 23
      docs_src/bigger_applications/app_an_py39/main.py
  28. 0
      docs_src/bigger_applications/app_an_py39/routers/__init__.py
  29. 38
      docs_src/bigger_applications/app_an_py39/routers/items.py
  30. 18
      docs_src/bigger_applications/app_an_py39/routers/users.py
  31. 0
      docs_src/bigger_applications/app_py39/__init__.py
  32. 11
      docs_src/bigger_applications/app_py39/dependencies.py
  33. 23
      docs_src/bigger_applications/app_py39/main.py
  34. 14
      docs_src/body_nested_models/tutorial008_py39.py
  35. 8
      docs_src/body_nested_models/tutorial009_py39.py
  36. 16
      docs_src/conditional_openapi/tutorial001_py39.py
  37. 8
      docs_src/configure_swagger_ui/tutorial001_py39.py
  38. 8
      docs_src/configure_swagger_ui/tutorial002_py39.py
  39. 8
      docs_src/configure_swagger_ui/tutorial003_py39.py
  40. 24
      docs_src/cors/tutorial001_py39.py
  41. 38
      docs_src/custom_docs_ui/tutorial001_py39.py
  42. 41
      docs_src/custom_docs_ui/tutorial002_py39.py
  43. 9
      docs_src/custom_response/tutorial001_py39.py
  44. 9
      docs_src/custom_response/tutorial001b_py39.py
  45. 18
      docs_src/custom_response/tutorial002_py39.py
  46. 19
      docs_src/custom_response/tutorial003_py39.py
  47. 23
      docs_src/custom_response/tutorial004_py39.py
  48. 9
      docs_src/custom_response/tutorial005_py39.py
  49. 9
      docs_src/custom_response/tutorial006_py39.py
  50. 9
      docs_src/custom_response/tutorial006b_py39.py
  51. 9
      docs_src/custom_response/tutorial006c_py39.py
  52. 14
      docs_src/custom_response/tutorial007_py39.py
  53. 14
      docs_src/custom_response/tutorial008_py39.py
  54. 10
      docs_src/custom_response/tutorial009_py39.py
  55. 10
      docs_src/custom_response/tutorial009b_py39.py
  56. 19
      docs_src/custom_response/tutorial009c_py39.py
  57. 9
      docs_src/custom_response/tutorial010_py39.py
  58. 15
      docs_src/debugging/tutorial001_py39.py
  59. 21
      docs_src/dependencies/tutorial006_an_py39.py
  60. 19
      docs_src/dependencies/tutorial006_py39.py
  61. 6
      docs_src/dependencies/tutorial007_py39.py
  62. 27
      docs_src/dependencies/tutorial008_an_py39.py
  63. 25
      docs_src/dependencies/tutorial008_py39.py
  64. 32
      docs_src/dependencies/tutorial008b_an_py39.py
  65. 30
      docs_src/dependencies/tutorial008b_py39.py
  66. 29
      docs_src/dependencies/tutorial008c_an_py39.py
  67. 27
      docs_src/dependencies/tutorial008c_py39.py
  68. 30
      docs_src/dependencies/tutorial008d_an_py39.py
  69. 28
      docs_src/dependencies/tutorial008d_py39.py
  70. 17
      docs_src/dependencies/tutorial008e_an_py39.py
  71. 15
      docs_src/dependencies/tutorial008e_py39.py
  72. 14
      docs_src/dependencies/tutorial010_py39.py
  73. 23
      docs_src/dependencies/tutorial011_an_py39.py
  74. 21
      docs_src/dependencies/tutorial011_py39.py
  75. 27
      docs_src/dependencies/tutorial012_an_py39.py
  76. 25
      docs_src/dependencies/tutorial012_py39.py
  77. 16
      docs_src/events/tutorial001_py39.py
  78. 14
      docs_src/events/tutorial002_py39.py
  79. 28
      docs_src/events/tutorial003_py39.py
  80. 29
      docs_src/extending_openapi/tutorial001_py39.py
  81. 20
      docs_src/extra_models/tutorial004_py39.py
  82. 8
      docs_src/extra_models/tutorial005_py39.py
  83. 8
      docs_src/first_steps/tutorial001_py39.py
  84. 8
      docs_src/first_steps/tutorial003_py39.py
  85. 26
      docs_src/generate_clients/tutorial001_py39.py
  86. 36
      docs_src/generate_clients/tutorial002_py39.py
  87. 42
      docs_src/generate_clients/tutorial003_py39.py
  88. 15
      docs_src/generate_clients/tutorial004_py39.py
  89. 25
      docs_src/graphql_/tutorial001_py39.py
  90. 12
      docs_src/handling_errors/tutorial001_py39.py
  91. 16
      docs_src/handling_errors/tutorial002_py39.py
  92. 25
      docs_src/handling_errors/tutorial003_py39.py
  93. 26
      docs_src/handling_errors/tutorial004_py39.py
  94. 25
      docs_src/handling_errors/tutorial005_py39.py
  95. 28
      docs_src/handling_errors/tutorial006_py39.py
  96. 38
      docs_src/metadata/tutorial001_1_py39.py
  97. 38
      docs_src/metadata/tutorial001_py39.py
  98. 8
      docs_src/metadata/tutorial002_py39.py
  99. 8
      docs_src/metadata/tutorial003_py39.py
  100. 28
      docs_src/metadata/tutorial004_py39.py

22
docs_src/additional_responses/tutorial001_py39.py

@ -1,22 +0,0 @@
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"})

37
docs_src/additional_responses/tutorial003_py39.py

@ -1,37 +0,0 @@
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"})

11
docs_src/advanced_middleware/tutorial001_py39.py

@ -1,11 +0,0 @@
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"}

13
docs_src/advanced_middleware/tutorial002_py39.py

@ -1,13 +0,0 @@
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"}

11
docs_src/advanced_middleware/tutorial003_py39.py

@ -1,11 +0,0 @@
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"

0
docs_src/app_testing/app_a_py39/__init__.py

8
docs_src/app_testing/app_a_py39/main.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_main():
return {"msg": "Hello World"}

11
docs_src/app_testing/app_a_py39/test_main.py

@ -1,11 +0,0 @@
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"}

18
docs_src/app_testing/tutorial001_py39.py

@ -1,18 +0,0 @@
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"}

31
docs_src/app_testing/tutorial002_py39.py

@ -1,31 +0,0 @@
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"}

24
docs_src/app_testing/tutorial003_py39.py

@ -1,24 +0,0 @@
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"}

43
docs_src/app_testing/tutorial004_py39.py

@ -1,43 +0,0 @@
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 == {}

0
docs_src/async_tests/app_a_py39/__init__.py

8
docs_src/async_tests/app_a_py39/main.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Tomato"}

14
docs_src/async_tests/app_a_py39/test_main.py

@ -1,14 +0,0 @@
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"}

21
docs_src/authentication_error_status_code/tutorial001_an_py39.py

@ -1,21 +0,0 @@
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}

15
docs_src/background_tasks/tutorial001_py39.py

@ -1,15 +0,0 @@
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"}

8
docs_src/behind_a_proxy/tutorial001_01_py39.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_items():
return ["plumbus", "portal gun"]

8
docs_src/behind_a_proxy/tutorial001_py39.py

@ -1,8 +0,0 @@
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")}

8
docs_src/behind_a_proxy/tutorial002_py39.py

@ -1,8 +0,0 @@
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")}

14
docs_src/behind_a_proxy/tutorial003_py39.py

@ -1,14 +0,0 @@
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")}

15
docs_src/behind_a_proxy/tutorial004_py39.py

@ -1,15 +0,0 @@
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")}

0
docs_src/bigger_applications/app_an_py39/__init__.py

13
docs_src/bigger_applications/app_an_py39/dependencies.py

@ -1,13 +0,0 @@
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")

0
docs_src/bigger_applications/app_an_py39/internal/__init__.py

8
docs_src/bigger_applications/app_an_py39/internal/admin.py

@ -1,8 +0,0 @@
from fastapi import APIRouter
router = APIRouter()
@router.post("/")
async def update_admin():
return {"message": "Admin getting schwifty"}

23
docs_src/bigger_applications/app_an_py39/main.py

@ -1,23 +0,0 @@
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!"}

0
docs_src/bigger_applications/app_an_py39/routers/__init__.py

38
docs_src/bigger_applications/app_an_py39/routers/items.py

@ -1,38 +0,0 @@
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": {"name": "Portal Gun"}}
@router.get("/")
async def read_items():
return fake_items_db
@router.get("/{item_id}")
async def read_item(item_id: str):
if item_id not in fake_items_db:
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": "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 great Plumbus"}

18
docs_src/bigger_applications/app_an_py39/routers/users.py

@ -1,18 +0,0 @@
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/", tags=["users"])
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]
@router.get("/users/me", tags=["users"])
async def read_user_me():
return {"username": "fakecurrentuser"}
@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
return {"username": username}

0
docs_src/bigger_applications/app_py39/__init__.py

11
docs_src/bigger_applications/app_py39/dependencies.py

@ -1,11 +0,0 @@
from fastapi import Header, HTTPException
async def get_token_header(x_token: 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")

23
docs_src/bigger_applications/app_py39/main.py

@ -1,23 +0,0 @@
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!"}

14
docs_src/body_nested_models/tutorial008_py39.py

@ -1,14 +0,0 @@
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

8
docs_src/body_nested_models/tutorial009_py39.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI()
@app.post("/index-weights/")
async def create_index_weights(weights: dict[int, float]):
return weights

16
docs_src/conditional_openapi/tutorial001_py39.py

@ -1,16 +0,0 @@
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"}

8
docs_src/configure_swagger_ui/tutorial001_py39.py

@ -1,8 +0,0 @@
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}"}

8
docs_src/configure_swagger_ui/tutorial002_py39.py

@ -1,8 +0,0 @@
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}"}

8
docs_src/configure_swagger_ui/tutorial003_py39.py

@ -1,8 +0,0 @@
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}"}

24
docs_src/cors/tutorial001_py39.py

@ -1,24 +0,0 @@
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"}

38
docs_src/custom_docs_ui/tutorial001_py39.py

@ -1,38 +0,0 @@
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}"}

41
docs_src/custom_docs_ui/tutorial002_py39.py

@ -1,41 +0,0 @@
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}"}

9
docs_src/custom_response/tutorial001_py39.py

@ -1,9 +0,0 @@
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"}]

9
docs_src/custom_response/tutorial001b_py39.py

@ -1,9 +0,0 @@
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"}])

18
docs_src/custom_response/tutorial002_py39.py

@ -1,18 +0,0 @@
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>
"""

19
docs_src/custom_response/tutorial003_py39.py

@ -1,19 +0,0 @@
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)

23
docs_src/custom_response/tutorial004_py39.py

@ -1,23 +0,0 @@
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()

9
docs_src/custom_response/tutorial005_py39.py

@ -1,9 +0,0 @@
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
app = FastAPI()
@app.get("/", response_class=PlainTextResponse)
async def main():
return "Hello World"

9
docs_src/custom_response/tutorial006_py39.py

@ -1,9 +0,0 @@
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/typer")
async def redirect_typer():
return RedirectResponse("https://typer.tiangolo.com")

9
docs_src/custom_response/tutorial006b_py39.py

@ -1,9 +0,0 @@
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"

9
docs_src/custom_response/tutorial006c_py39.py

@ -1,9 +0,0 @@
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/"

14
docs_src/custom_response/tutorial007_py39.py

@ -1,14 +0,0 @@
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"
@app.get("/")
async def main():
return StreamingResponse(fake_video_streamer())

14
docs_src/custom_response/tutorial008_py39.py

@ -1,14 +0,0 @@
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")

10
docs_src/custom_response/tutorial009_py39.py

@ -1,10 +0,0 @@
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)

10
docs_src/custom_response/tutorial009b_py39.py

@ -1,10 +0,0 @@
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

19
docs_src/custom_response/tutorial009c_py39.py

@ -1,19 +0,0 @@
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"}

9
docs_src/custom_response/tutorial010_py39.py

@ -1,9 +0,0 @@
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
app = FastAPI(default_response_class=ORJSONResponse)
@app.get("/items/")
async def read_items():
return [{"item_id": "Foo"}]

15
docs_src/debugging/tutorial001_py39.py

@ -1,15 +0,0 @@
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)

21
docs_src/dependencies/tutorial006_an_py39.py

@ -1,21 +0,0 @@
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"}]

19
docs_src/dependencies/tutorial006_py39.py

@ -1,19 +0,0 @@
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"}]

6
docs_src/dependencies/tutorial007_py39.py

@ -1,6 +0,0 @@
async def get_db():
db = DBSession()
try:
yield db
finally:
db.close()

27
docs_src/dependencies/tutorial008_an_py39.py

@ -1,27 +0,0 @@
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)

25
docs_src/dependencies/tutorial008_py39.py

@ -1,25 +0,0 @@
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)

32
docs_src/dependencies/tutorial008b_an_py39.py

@ -1,32 +0,0 @@
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

30
docs_src/dependencies/tutorial008b_py39.py

@ -1,30 +0,0 @@
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

29
docs_src/dependencies/tutorial008c_an_py39.py

@ -1,29 +0,0 @@
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

27
docs_src/dependencies/tutorial008c_py39.py

@ -1,27 +0,0 @@
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

30
docs_src/dependencies/tutorial008d_an_py39.py

@ -1,30 +0,0 @@
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

28
docs_src/dependencies/tutorial008d_py39.py

@ -1,28 +0,0 @@
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

17
docs_src/dependencies/tutorial008e_an_py39.py

@ -1,17 +0,0 @@
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

15
docs_src/dependencies/tutorial008e_py39.py

@ -1,15 +0,0 @@
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

14
docs_src/dependencies/tutorial010_py39.py

@ -1,14 +0,0 @@
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

23
docs_src/dependencies/tutorial011_an_py39.py

@ -1,23 +0,0 @@
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}

21
docs_src/dependencies/tutorial011_py39.py

@ -1,21 +0,0 @@
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}

27
docs_src/dependencies/tutorial012_an_py39.py

@ -1,27 +0,0 @@
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"}]

25
docs_src/dependencies/tutorial012_py39.py

@ -1,25 +0,0 @@
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"}]

16
docs_src/events/tutorial001_py39.py

@ -1,16 +0,0 @@
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]

14
docs_src/events/tutorial002_py39.py

@ -1,14 +0,0 @@
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"}]

28
docs_src/events/tutorial003_py39.py

@ -1,28 +0,0 @@
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}

29
docs_src/extending_openapi/tutorial001_py39.py

@ -1,29 +0,0 @@
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

20
docs_src/extra_models/tutorial004_py39.py

@ -1,20 +0,0 @@
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

8
docs_src/extra_models/tutorial005_py39.py

@ -1,8 +0,0 @@
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}

8
docs_src/first_steps/tutorial001_py39.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}

8
docs_src/first_steps/tutorial003_py39.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}

26
docs_src/generate_clients/tutorial001_py39.py

@ -1,26 +0,0 @@
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
class ResponseMessage(BaseModel):
message: str
@app.post("/items/", response_model=ResponseMessage)
async def create_item(item: Item):
return {"message": "item received"}
@app.get("/items/", response_model=list[Item])
async def get_items():
return [
{"name": "Plumbus", "price": 3},
{"name": "Portal Gun", "price": 9001},
]

36
docs_src/generate_clients/tutorial002_py39.py

@ -1,36 +0,0 @@
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
class ResponseMessage(BaseModel):
message: str
class User(BaseModel):
username: str
email: str
@app.post("/items/", response_model=ResponseMessage, tags=["items"])
async def create_item(item: Item):
return {"message": "Item received"}
@app.get("/items/", response_model=list[Item], tags=["items"])
async def get_items():
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"}

42
docs_src/generate_clients/tutorial003_py39.py

@ -1,42 +0,0 @@
from fastapi import FastAPI
from fastapi.routing import APIRoute
from pydantic import BaseModel
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
email: str
@app.post("/items/", response_model=ResponseMessage, tags=["items"])
async def create_item(item: Item):
return {"message": "Item received"}
@app.get("/items/", response_model=list[Item], tags=["items"])
async def get_items():
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"}

15
docs_src/generate_clients/tutorial004_py39.py

@ -1,15 +0,0 @@
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))

25
docs_src/graphql_/tutorial001_py39.py

@ -1,25 +0,0 @@
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")

12
docs_src/handling_errors/tutorial001_py39.py

@ -1,12 +0,0 @@
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]}

16
docs_src/handling_errors/tutorial002_py39.py

@ -1,16 +0,0 @@
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]}

25
docs_src/handling_errors/tutorial003_py39.py

@ -1,25 +0,0 @@
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}

26
docs_src/handling_errors/tutorial004_py39.py

@ -1,26 +0,0 @@
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}

25
docs_src/handling_errors/tutorial005_py39.py

@ -1,25 +0,0 @@
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

28
docs_src/handling_errors/tutorial006_py39.py

@ -1,28 +0,0 @@
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}

38
docs_src/metadata/tutorial001_1_py39.py

@ -1,38 +0,0 @@
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": "[email protected]",
},
license_info={
"name": "Apache 2.0",
"identifier": "Apache-2.0",
},
)
@app.get("/items/")
async def read_items():
return [{"name": "Katana"}]

38
docs_src/metadata/tutorial001_py39.py

@ -1,38 +0,0 @@
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": "[email protected]",
},
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"}]

8
docs_src/metadata/tutorial002_py39.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI(openapi_url="/api/v1/openapi.json")
@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]

8
docs_src/metadata/tutorial003_py39.py

@ -1,8 +0,0 @@
from fastapi import FastAPI
app = FastAPI(docs_url="/documentation", redoc_url=None)
@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]

28
docs_src/metadata/tutorial004_py39.py

@ -1,28 +0,0 @@
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"}]

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save