Skip to content

๐Ÿ“จ ๐Ÿ“จ ๐Ÿ”—

๐Ÿ•โ” ๐Ÿ‘† โœ FastAPI โžก ๐Ÿ› ๏ธ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ›Ž ๐Ÿ“จ ๐Ÿ™† ๐Ÿ“Š โšช๏ธโžก๏ธ โšซ๏ธ: dict, list, Pydantic ๐Ÿท, ๐Ÿ’ฝ ๐Ÿท, โ™’๏ธ.

๐Ÿ”ข, FastAPI ๐Ÿ”œ ๐Ÿ” ๐Ÿ—œ ๐Ÿ‘ˆ ๐Ÿ“จ ๐Ÿ’ฒ ๐ŸŽป โš™๏ธ jsonable_encoder ๐Ÿ”ฌ ๐ŸŽป ๐Ÿ”— ๐Ÿ”ข.

โคด๏ธ, โ›… ๐ŸŽ‘, โšซ๏ธ ๐Ÿ”œ ๐Ÿšฎ ๐Ÿ‘ˆ ๐ŸŽป-๐Ÿ”— ๐Ÿ’ฝ (โœ… dict) ๐Ÿ”˜ JSONResponse ๐Ÿ‘ˆ ๐Ÿ”œ โš™๏ธ ๐Ÿ“จ ๐Ÿ“จ ๐Ÿ‘ฉโ€๐Ÿ’ป.

โœ‹๏ธ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“จ JSONResponse ๐Ÿ”— โšช๏ธโžก๏ธ ๐Ÿ‘† โžก ๐Ÿ› ๏ธ.

โšซ๏ธ ๐Ÿ’ช โš , ๐Ÿ–ผ, ๐Ÿ“จ ๐Ÿ›ƒ ๐ŸŽš โš–๏ธ ๐Ÿช.

๐Ÿ“จ Response

๐Ÿ‘, ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“จ ๐Ÿ™† Response โš–๏ธ ๐Ÿ™† ๐ŸŽง-๐ŸŽ“ โšซ๏ธ.

Tip

JSONResponse โšซ๏ธ ๐ŸŽง-๐ŸŽ“ Response.

& ๐Ÿ•โ” ๐Ÿ‘† ๐Ÿ“จ Response, FastAPI ๐Ÿ”œ ๐Ÿšถโ€โ™€๏ธ โšซ๏ธ ๐Ÿ”—.

โšซ๏ธ ๐Ÿ† ๐Ÿšซ ๐Ÿ™† ๐Ÿ’ฝ ๐Ÿ› ๏ธ โฎ๏ธ Pydantic ๐Ÿท, โšซ๏ธ ๐Ÿ† ๐Ÿšซ ๐Ÿ—œ ๐ŸŽš ๐Ÿ™† ๐Ÿ†Ž, โ™’๏ธ.

๐Ÿ‘‰ ๐Ÿค ๐Ÿ‘† ๐Ÿ“š ๐Ÿ’ช. ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“จ ๐Ÿ™† ๐Ÿ“Š ๐Ÿ†Ž, ๐Ÿ” ๐Ÿ™† ๐Ÿ’ฝ ๐Ÿ“„ โš–๏ธ ๐Ÿ”ฌ, โ™’๏ธ.

โš™๏ธ jsonable_encoder Response

โ†ฉ๏ธ FastAPI ๐Ÿšซ ๐Ÿ™† ๐Ÿ”€ Response ๐Ÿ‘† ๐Ÿ“จ, ๐Ÿ‘† โœ”๏ธ โš’ ๐Ÿ’ญ โšซ๏ธ ๐ŸŽš ๐Ÿ”œ โšซ๏ธ.

๐Ÿ–ผ, ๐Ÿ‘† ๐Ÿšซ๐Ÿ”œ ๐Ÿšฎ Pydantic ๐Ÿท JSONResponse ๐Ÿต ๐Ÿฅ‡ ๐Ÿญ โšซ๏ธ dict โฎ๏ธ ๐ŸŒ ๐Ÿ“Š ๐Ÿ†Ž (๐Ÿ’– datetime, UUID, โ™’๏ธ) ๐Ÿ—œ ๐ŸŽป-๐Ÿ”— ๐Ÿ†Ž.

๐Ÿ“š ๐Ÿ’ผ, ๐Ÿ‘† ๐Ÿ’ช โš™๏ธ jsonable_encoder ๐Ÿ—œ ๐Ÿ‘† ๐Ÿ“Š โญ ๐Ÿšถโ€โ™€๏ธ โšซ๏ธ ๐Ÿ“จ:

from datetime import datetime
from typing import Union

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: Union[str, None] = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    return JSONResponse(content=json_compatible_item_data)

๐Ÿ“ก โ„น

๐Ÿ‘† ๐Ÿ’ช โš™๏ธ from starlette.responses import JSONResponse.

FastAPI ๐Ÿšš ๐ŸŽ starlette.responses fastapi.responses ๐Ÿช ๐Ÿ‘†, ๐Ÿ‘ฉโ€๐Ÿ’ป. โœ‹๏ธ ๐ŸŒ… ๐Ÿ’ช ๐Ÿ“จ ๐Ÿ‘Ÿ ๐Ÿ”— โšช๏ธโžก๏ธ ๐Ÿ’ƒ.

๐Ÿ›ฌ ๐Ÿ›ƒ Response

๐Ÿ–ผ ๐Ÿ”› ๐ŸŽฆ ๐ŸŒ ๐Ÿ• ๐Ÿ‘† ๐Ÿ’ช, โœ‹๏ธ โšซ๏ธ ๐Ÿšซ ๐Ÿ“ถ โš , ๐Ÿ‘† ๐Ÿ’ช โœ”๏ธ ๐Ÿ“จ item ๐Ÿ”—, & FastAPI ๐Ÿ”œ ๐Ÿšฎ โšซ๏ธ JSONResponse ๐Ÿ‘†, ๐Ÿญ โšซ๏ธ dict, โ™’๏ธ. ๐ŸŒ ๐Ÿ‘ˆ ๐Ÿ”ข.

๐Ÿ”œ, โžก๏ธ ๐Ÿ‘€ โ” ๐Ÿ‘† ๐Ÿ’ช โš™๏ธ ๐Ÿ‘ˆ ๐Ÿ“จ ๐Ÿ›ƒ ๐Ÿ“จ.

โžก๏ธ ๐Ÿ’ฌ ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ’š ๐Ÿ“จ ๐Ÿ“‚ ๐Ÿ“จ.

๐Ÿ‘† ๐Ÿ’ช ๐Ÿšฎ ๐Ÿ‘† ๐Ÿ“‚ ๐ŸŽš ๐ŸŽป, ๐Ÿšฎ โšซ๏ธ Response, & ๐Ÿ“จ โšซ๏ธ:

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/legacy/")
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml")

๐Ÿ—’

๐Ÿ•โ” ๐Ÿ‘† ๐Ÿ“จ Response ๐Ÿ”— ๐Ÿšฎ ๐Ÿ“Š ๐Ÿšซ โœ”, ๐Ÿ—œ (๐ŸŽป), ๐Ÿšซ ๐Ÿ“„ ๐Ÿ”.

โœ‹๏ธ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“„ โšซ๏ธ ๐Ÿ”ฌ ๐ŸŒ– ๐Ÿ“จ ๐Ÿ—„.

๐Ÿ‘† ๐Ÿ’ช ๐Ÿ‘€ โช ๐Ÿ“„ โ” โš™๏ธ/๐Ÿ“ฃ ๐Ÿ‘‰ ๐Ÿ›ƒ Responseโ“‚ โช โœ”๏ธ ๐Ÿง ๐Ÿ’ฝ ๐Ÿ› ๏ธ, ๐Ÿงพ, โ™’๏ธ.