Skip to content

🚚 ❌

📤 📚 ⚠ 🌐❔ 👆 💪 🚨 ❌ 👩‍💻 👈 ⚙️ 👆 🛠️.

👉 👩‍💻 💪 🖥 ⏮️ 🕸, 📟 ⚪️➡️ 👱 🙆, ☁ 📳, ♒️.

👆 💪 💪 💬 👩‍💻 👈:

  • 👩‍💻 🚫 ✔️ 🥃 😌 👈 🛠️.
  • 👩‍💻 🚫 ✔️ 🔐 👈 ℹ.
  • 🏬 👩‍💻 🔄 🔐 🚫 🔀.
  • ♒️.

👫 💼, 👆 🔜 🛎 📨 🇺🇸🔍 👔 📟4️⃣0️⃣0️⃣ (⚪️➡️ 4️⃣0️⃣0️⃣ 4️⃣9️⃣9️⃣).

👉 🎏 2️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟 (⚪️➡️ 2️⃣0️⃣0️⃣ 2️⃣9️⃣9️⃣). 👈 "2️⃣0️⃣0️⃣" 👔 📟 ⛓ 👈 😫 📤 "🏆" 📨.

👔 📟 4️⃣0️⃣0️⃣ ↔ ⛓ 👈 📤 ❌ ⚪️➡️ 👩‍💻.

💭 🌐 👈 "4️⃣0️⃣4️⃣ 🚫 🔎" ❌ (& 🤣) ❓

⚙️ HTTPException

📨 🇺🇸🔍 📨 ⏮️ ❌ 👩‍💻 👆 ⚙️ HTTPException.

🗄 HTTPException

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]}

🤚 HTTPException 👆 📟

HTTPException 😐 🐍 ⚠ ⏮️ 🌖 📊 🔗 🔗.

↩️ ⚫️ 🐍 ⚠, 👆 🚫 return ⚫️, 👆 raise ⚫️.

👉 ⛓ 👈 🚥 👆 🔘 🚙 🔢 👈 👆 🤙 🔘 👆 ➡ 🛠️ 🔢, & 👆 🤚 HTTPException ⚪️➡️ 🔘 👈 🚙 🔢, ⚫️ 🏆 🚫 🏃 🎂 📟 ➡ 🛠️ 🔢, ⚫️ 🔜 ❎ 👈 📨 ▶️️ ↖️ & 📨 🇺🇸🔍 ❌ ⚪️➡️ HTTPException 👩‍💻.

💰 🙋‍♀ ⚠ 🤭 return😅 💲 🔜 🌖 ⭐ 📄 🔃 🔗 & 💂‍♂.

👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 404:

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]}

📉 📨

🚥 👩‍💻 📨 http://example.com/items/foo ( item_id "foo"), 👈 👩‍💻 🔜 📨 🇺🇸🔍 👔 📟 2️⃣0️⃣0️⃣, & 🎻 📨:

{
  "item": "The Foo Wrestlers"
}

✋️ 🚥 👩‍💻 📨 http://example.com/items/bar (🚫-🚫 item_id "bar"), 👈 👩‍💻 🔜 📨 🇺🇸🔍 👔 📟 4️⃣0️⃣4️⃣ ("🚫 🔎" ❌), & 🎻 📨:

{
  "detail": "Item not found"
}

Tip

🕐❔ 🙋‍♀ HTTPException, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 detail, 🚫 🕴 str.

👆 💪 🚶‍♀️ dict, list, ♒️.

👫 🍵 🔁 FastAPI & 🗜 🎻.

🚮 🛃 🎚

📤 ⚠ 🌐❔ ⚫️ ⚠ 💪 🚮 🛃 🎚 🇺🇸🔍 ❌. 🖼, 🆎 💂‍♂.

👆 🎲 🏆 🚫 💪 ⚙️ ⚫️ 🔗 👆 📟.

✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚:

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]}

❎ 🛃 ⚠ 🐕‍🦺

👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ 🎏 ⚠ 🚙 ⚪️➡️ 💃.

➡️ 💬 👆 ✔️ 🛃 ⚠ UnicornException 👈 👆 (⚖️ 🗃 👆 ⚙️) 💪 raise.

& 👆 💚 🍵 👉 ⚠ 🌐 ⏮️ FastAPI.

👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ @app.exception_handler():

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}

📥, 🚥 👆 📨 /unicorns/yolo, ➡ 🛠️ 🔜 raise UnicornException.

✋️ ⚫️ 🔜 🍵 unicorn_exception_handler.

, 👆 🔜 📨 🧹 ❌, ⏮️ 🇺🇸🔍 👔 📟 418 & 🎻 🎚:

{"message": "Oops! yolo did something. There goes a rainbow..."}

📡 ℹ

👆 💪 ⚙️ from starlette.requests import Request & from starlette.responses import JSONResponse.

FastAPI 🚚 🎏 starlette.responses fastapi.responses 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ Request.

🔐 🔢 ⚠ 🐕‍🦺

FastAPI ✔️ 🔢 ⚠ 🐕‍🦺.

👫 🐕‍🦺 🈚 🛬 🔢 🎻 📨 🕐❔ 👆 raise HTTPException & 🕐❔ 📨 ✔️ ❌ 💽.

👆 💪 🔐 👫 ⚠ 🐕‍🦺 ⏮️ 👆 👍.

🔐 📨 🔬 ⚠

🕐❔ 📨 🔌 ❌ 📊, FastAPI 🔘 🤚 RequestValidationError.

& ⚫️ 🔌 🔢 ⚠ 🐕‍🦺 ⚫️.

🔐 ⚫️, 🗄 RequestValidationError & ⚙️ ⚫️ ⏮️ @app.exception_handler(RequestValidationError) 🎀 ⚠ 🐕‍🦺.

⚠ 🐕‍🦺 🔜 📨 Request & ⚠.

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):
    return PlainTextResponse(str(exc), 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}

🔜, 🚥 👆 🚶 /items/foo, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️:

{
    "detail": [
        {
            "loc": [
                "path",
                "item_id"
            ],
            "msg": "value is not a valid integer",
            "type": "type_error.integer"
        }
    ]
}

👆 🔜 🤚 ✍ ⏬, ⏮️:

1 validation error
path -> item_id
  value is not a valid integer (type=type_error.integer)

RequestValidationError 🆚 ValidationError

Warning

👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜.

RequestValidationError 🎧-🎓 Pydantic ValidationError.

FastAPI ⚙️ ⚫️ 👈, 🚥 👆 ⚙️ Pydantic 🏷 response_model, & 👆 💽 ✔️ ❌, 👆 🔜 👀 ❌ 👆 🕹.

✋️ 👩‍💻/👩‍💻 🔜 🚫 👀 ⚫️. ↩️, 👩‍💻 🔜 📨 "🔗 💽 ❌" ⏮️ 🇺🇸🔍 👔 📟 500.

⚫️ 🔜 👉 🌌 ↩️ 🚥 👆 ✔️ Pydantic ValidationError 👆 📨 ⚖️ 🙆 👆 📟 (🚫 👩‍💻 📨), ⚫️ 🤙 🐛 👆 📟.

& ⏪ 👆 🔧 ⚫️, 👆 👩‍💻/👩‍💻 🚫🔜 🚫 ✔️ 🔐 🔗 ℹ 🔃 ❌, 👈 💪 🎦 💂‍♂ ⚠.

🔐 HTTPException ❌ 🐕‍🦺

🎏 🌌, 👆 💪 🔐 HTTPException 🐕‍🦺.

🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌:

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):
    return PlainTextResponse(str(exc), 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}

📡 ℹ

👆 💪 ⚙️ from starlette.responses import PlainTextResponse.

FastAPI 🚚 🎏 starlette.responses fastapi.responses 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.

⚙️ RequestValidationError 💪

RequestValidationError 🔌 body ⚫️ 📨 ⏮️ ❌ 💽.

👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️.

from fastapi import FastAPI, Request, status
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=status.HTTP_422_UNPROCESSABLE_ENTITY,
        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

🔜 🔄 📨 ❌ 🏬 💖:

{
  "title": "towel",
  "size": "XL"
}

👆 🔜 📨 📨 💬 👆 👈 💽 ❌ ⚗ 📨 💪:

{
  "detail": [
    {
      "loc": [
        "body",
        "size"
      ],
      "msg": "value is not a valid integer",
      "type": "type_error.integer"
    }
  ],
  "body": {
    "title": "towel",
    "size": "XL"
  }
}

FastAPI HTTPException 🆚 💃 HTTPException

FastAPI ✔️ 🚮 👍 HTTPException.

& FastAPI'Ⓜ HTTPException ❌ 🎓 😖 ⚪️➡️ 💃 HTTPException ❌ 🎓.

🕴 🔺, 👈 FastAPI'Ⓜ HTTPException ✔ 👆 🚮 🎚 🔌 📨.

👉 💪/⚙️ 🔘 ✳ 2️⃣.0️⃣ & 💂‍♂ 🚙.

, 👆 💪 🚧 🙋‍♀ FastAPI'Ⓜ HTTPException 🛎 👆 📟.

✋️ 🕐❔ 👆 ® ⚠ 🐕‍🦺, 👆 🔜 ® ⚫️ 💃 HTTPException.

👉 🌌, 🚥 🙆 🍕 💃 🔗 📟, ⚖️ 💃 ↔ ⚖️ 🔌 -, 🤚 💃 HTTPException, 👆 🐕‍🦺 🔜 💪 ✊ & 🍵 ⚫️.

👉 🖼, 💪 ✔️ 👯‍♂️ HTTPExceptionⓂ 🎏 📟, 💃 ⚠ 📁 StarletteHTTPException:

from starlette.exceptions import HTTPException as StarletteHTTPException

🏤-⚙️ FastAPI'Ⓜ ⚠ 🐕‍🦺

🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ FastAPI, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ fastapi.exception_handlers:

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}

👉 🖼 👆 print😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺.