Skip to content

🌖 📨 🗄

Warning

👉 👍 🏧 ❔.

🚥 👆 ▶️ ⏮️ FastAPI, 👆 💪 🚫 💪 👉.

👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️.

👈 🌖 📨 🔜 🔌 🗄 🔗, 👫 🔜 😑 🛠️ 🩺.

✋️ 👈 🌖 📨 👆 ✔️ ⚒ 💭 👆 📨 Response 💖 JSONResponse 🔗, ⏮️ 👆 👔 📟 & 🎚.

🌖 📨 ⏮️ model

👆 💪 🚶‍♀️ 👆 ➡ 🛠️ 👨‍🎨 🔢 responses.

⚫️ 📨 dict, 🔑 👔 📟 🔠 📨, 💖 200, & 💲 🎏 dictⓂ ⏮️ ℹ 🔠 👫.

🔠 👈 📨 dictⓂ 💪 ✔️ 🔑 model, ⚗ Pydantic 🏷, 💖 response_model.

FastAPI 🔜 ✊ 👈 🏷, 🏗 🚮 🎻 🔗 & 🔌 ⚫️ ☑ 🥉 🗄.

🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 404 & Pydantic 🏷 Message, 👆 💪 ✍:

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"})

Note

✔️ 🤯 👈 👆 ✔️ 📨 JSONResponse 🔗.

Info

model 🔑 🚫 🍕 🗄.

FastAPI 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 JSON Schema, & 🚮 ⚫️ ☑ 🥉.

☑ 🥉:

  • 🔑 content, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (dict) 👈 🔌:
    • 🔑 ⏮️ 📻 🆎, ✅ application/json, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
      • 🔑 schema, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
        • FastAPI 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩‍💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.

🏗 📨 🗄 👉 ➡ 🛠️ 🔜:

{
    "responses": {
        "404": {
            "description": "Additional Response",
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/Message"
                    }
                }
            }
        },
        "200": {
            "description": "Successful Response",
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/Item"
                    }
                }
            }
        },
        "422": {
            "description": "Validation Error",
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/HTTPValidationError"
                    }
                }
            }
        }
    }
}

🔗 🔗 ➕1️⃣ 🥉 🔘 🗄 🔗:

{
    "components": {
        "schemas": {
            "Message": {
                "title": "Message",
                "required": [
                    "message"
                ],
                "type": "object",
                "properties": {
                    "message": {
                        "title": "Message",
                        "type": "string"
                    }
                }
            },
            "Item": {
                "title": "Item",
                "required": [
                    "id",
                    "value"
                ],
                "type": "object",
                "properties": {
                    "id": {
                        "title": "Id",
                        "type": "string"
                    },
                    "value": {
                        "title": "Value",
                        "type": "string"
                    }
                }
            },
            "ValidationError": {
                "title": "ValidationError",
                "required": [
                    "loc",
                    "msg",
                    "type"
                ],
                "type": "object",
                "properties": {
                    "loc": {
                        "title": "Location",
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    },
                    "msg": {
                        "title": "Message",
                        "type": "string"
                    },
                    "type": {
                        "title": "Error Type",
                        "type": "string"
                    }
                }
            },
            "HTTPValidationError": {
                "title": "HTTPValidationError",
                "type": "object",
                "properties": {
                    "detail": {
                        "title": "Detail",
                        "type": "array",
                        "items": {
                            "$ref": "#/components/schemas/ValidationError"
                        }
                    }
                }
            }
        }
    }
}

🌖 🔉 🆎 👑 📨

👆 💪 ⚙️ 👉 🎏 responses 🔢 🚮 🎏 🔉 🆎 🎏 👑 📨.

🖼, 👆 💪 🚮 🌖 📻 🆎 image/png, 📣 👈 👆 ➡ 🛠️ 💪 📨 🎻 🎚 (⏮️ 📻 🆎 application/json) ⚖️ 🇩🇴 🖼:

from typing import Union

from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    value: str


app = FastAPI()


@app.get(
    "/items/{item_id}",
    response_model=Item,
    responses={
        200: {
            "content": {"image/png": {}},
            "description": "Return the JSON item or an image.",
        }
    },
)
async def read_item(item_id: str, img: Union[bool, None] = None):
    if img:
        return FileResponse("image.png", media_type="image/png")
    else:
        return {"id": "foo", "value": "there goes my hero"}

Note

👀 👈 👆 ✔️ 📨 🖼 ⚙️ FileResponse 🔗.

Info

🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 responses 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 application/json).

✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ None 🚮 📻 🆎, FastAPI 🔜 ⚙️ application/json 🙆 🌖 📨 👈 ✔️ 👨‍💼 🏷.

🌀 ℹ

👆 💪 🌀 📨 ℹ ⚪️➡️ 💗 🥉, 🔌 response_model, status_code, & responses 🔢.

👆 💪 📣 response_model, ⚙️ 🔢 👔 📟 200 (⚖️ 🛃 1️⃣ 🚥 👆 💪), & ⤴️ 📣 🌖 ℹ 👈 🎏 📨 responses, 🔗 🗄 🔗.

FastAPI 🔜 🚧 🌖 ℹ ⚪️➡️ responses, & 🌀 ⚫️ ⏮️ 🎻 🔗 ⚪️➡️ 👆 🏷.

🖼, 👆 💪 📣 📨 ⏮️ 👔 📟 404 👈 ⚙️ Pydantic 🏷 & ✔️ 🛃 description.

& 📨 ⏮️ 👔 📟 200 👈 ⚙️ 👆 response_model, ✋️ 🔌 🛃 example:

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"})

⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺:

🌀 🔢 📨 & 🛃 🕐

👆 💪 💚 ✔️ 🔁 📨 👈 ✔ 📚 ➡ 🛠️, ✋️ 👆 💚 🌀 👫 ⏮️ 🛃 📨 💚 🔠 ➡ 🛠️.

📚 💼, 👆 💪 ⚙️ 🐍 ⚒ "🏗" dict ⏮️ **dict_to_unpack:

old_dict = {
    "old key": "old value",
    "second old key": "second old value",
}
new_dict = {**old_dict, "new key": "new value"}

📥, new_dict 🔜 🔌 🌐 🔑-💲 👫 ⚪️➡️ old_dict ➕ 🆕 🔑-💲 👫:

{
    "old key": "old value",
    "second old key": "second old value",
    "new key": "new value",
}

👆 💪 ⚙️ 👈 ⚒ 🏤-⚙️ 🔢 📨 👆 ➡ 🛠️ & 🌀 👫 ⏮️ 🌖 🛃 🕐.

🖼:

from typing import Union

from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    value: str


responses = {
    404: {"description": "Item not found"},
    302: {"description": "The item was moved"},
    403: {"description": "Not enough privileges"},
}


app = FastAPI()


@app.get(
    "/items/{item_id}",
    response_model=Item,
    responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: Union[bool, None] = None):
    if img:
        return FileResponse("image.png", media_type="image/png")
    else:
        return {"id": "foo", "value": "there goes my hero"}

🌖 ℹ 🔃 🗄 📨

👀 ⚫️❔ ⚫️❔ 👆 💪 🔌 📨, 👆 💪 ✅ 👉 📄 🗄 🔧:

  • 🗄 📨 🎚, ⚫️ 🔌 Response Object.
  • 🗄 📨 🎚, 👆 💪 🔌 🕳 ⚪️➡️ 👉 🔗 🔠 📨 🔘 👆 responses 🔢. ✅ description, headers, content (🔘 👉 👈 👆 📣 🎏 🔉 🆎 & 🎻 🔗), & links.