Skip to content

๐ŸŒ– ๐Ÿ‘” ๐Ÿ“Ÿ

๐Ÿ”ข, FastAPI ๐Ÿ”œ ๐Ÿ“จ ๐Ÿ“จ โš™๏ธ JSONResponse, ๐Ÿšฎ ๐ŸŽš ๐Ÿ‘† ๐Ÿ“จ โšช๏ธโžก๏ธ ๐Ÿ‘† โžก ๐Ÿ› ๏ธ ๐Ÿ”˜ ๐Ÿ‘ˆ JSONResponse.

โšซ๏ธ ๐Ÿ”œ โš™๏ธ ๐Ÿ”ข ๐Ÿ‘” ๐Ÿ“Ÿ โš–๏ธ 1๏ธโƒฃ ๐Ÿ‘† โš’ ๐Ÿ‘† โžก ๐Ÿ› ๏ธ.

๐ŸŒ– ๐Ÿ‘” ๐Ÿ“Ÿ

๐Ÿšฅ ๐Ÿ‘† ๐Ÿ’š ๐Ÿ“จ ๐ŸŒ– ๐Ÿ‘” ๐Ÿ“Ÿ โ†–๏ธ โšช๏ธโžก๏ธ ๐Ÿ‘‘ 1๏ธโƒฃ, ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ‘ˆ ๐Ÿ›ฌ Response ๐Ÿ”—, ๐Ÿ’– JSONResponse, & โš’ ๐ŸŒ– ๐Ÿ‘” ๐Ÿ“Ÿ ๐Ÿ”—.

๐Ÿ–ผ, โžก๏ธ ๐Ÿ’ฌ ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ’š โœ”๏ธ โžก ๐Ÿ› ๏ธ ๐Ÿ‘ˆ โœ” โ„น ๐Ÿฌ, & ๐Ÿ“จ ๐Ÿ‡บ๐Ÿ‡ธ๐Ÿ” ๐Ÿ‘” ๐Ÿ“Ÿ 2๏ธโƒฃ0๏ธโƒฃ0๏ธโƒฃ "๐Ÿ‘Œ" ๐Ÿ•โ” ๐Ÿ†.

โœ‹๏ธ ๐Ÿ‘† ๐Ÿ’š โšซ๏ธ ๐Ÿšซ ๐Ÿ†• ๐Ÿฌ. & ๐Ÿ•โ” ๐Ÿฌ ๐Ÿšซ ๐Ÿ”€ โญ, โšซ๏ธ โœ ๐Ÿ‘ซ, & ๐Ÿ“จ ๐Ÿ‡บ๐Ÿ‡ธ๐Ÿ” ๐Ÿ‘” ๐Ÿ“Ÿ 2๏ธโƒฃ0๏ธโƒฃ1๏ธโƒฃ "โœ".

๐Ÿ† ๐Ÿ‘ˆ, ๐Ÿ—„ JSONResponse, & ๐Ÿ“จ ๐Ÿ‘† ๐ŸŽš ๐Ÿ“ค ๐Ÿ”—, โš’ status_code ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ’š:

from typing import Union

from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}


@app.put("/items/{item_id}")
async def upsert_item(
    item_id: str,
    name: Union[str, None] = Body(default=None),
    size: Union[int, None] = Body(default=None),
):
    if item_id in items:
        item = items[item_id]
        item["name"] = name
        item["size"] = size
        return item
    else:
        item = {"name": name, "size": size}
        items[item_id] = item
        return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)

Warning

๐Ÿ•โ” ๐Ÿ‘† ๐Ÿ“จ Response ๐Ÿ”—, ๐Ÿ’– ๐Ÿ–ผ ๐Ÿ”›, โšซ๏ธ ๐Ÿ”œ ๐Ÿ“จ ๐Ÿ”—.

โšซ๏ธ ๐Ÿ† ๐Ÿšซ ๐ŸŽป โฎ๏ธ ๐Ÿท, โ™’๏ธ.

โš’ ๐Ÿ’ญ โšซ๏ธ โœ”๏ธ ๐Ÿ“Š ๐Ÿ‘† ๐Ÿ’š โšซ๏ธ โœ”๏ธ, & ๐Ÿ‘ˆ ๐Ÿ’ฒ โ˜‘ ๐ŸŽป (๐Ÿšฅ ๐Ÿ‘† โš™๏ธ JSONResponse).

๐Ÿ“ก โ„น

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

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

๐Ÿ—„ & ๐Ÿ› ๏ธ ๐Ÿฉบ

๐Ÿšฅ ๐Ÿ‘† ๐Ÿ“จ ๐ŸŒ– ๐Ÿ‘” ๐Ÿ“Ÿ & ๐Ÿ“จ ๐Ÿ”—, ๐Ÿ‘ซ ๐Ÿ† ๐Ÿšซ ๐Ÿ”Œ ๐Ÿ—„ ๐Ÿ”— (๐Ÿ› ๏ธ ๐Ÿฉบ), โ†ฉ๏ธ FastAPI ๐Ÿšซ โœ”๏ธ ๐ŸŒŒ ๐Ÿ’ญ โช โšซ๏ธโ” ๐Ÿ‘† ๐Ÿšถ ๐Ÿ“จ.

โœ‹๏ธ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“„ ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ“Ÿ, โš™๏ธ: ๐ŸŒ– ๐Ÿ“จ.