0
0

More than 1 year has passed since last update.

[FastAPI]レスポンスのキーに日本語を使う方法[Pydantic]

Last updated at Posted at 2022-11-02

FastAPIは日本語に対応しているが一工夫すると吉

まず、下記の様なレスポンスは何の問題も無く動作する。

from fastapi import FastAPI

app = FastAPI()
@app.get("/jp")
def jp():
    return {"こんにちは": "hello"}

しかし、FastAPIの大きな利点であるPydanticを使った型バリデーション及び自動型変換を使用すると日本語が使えなくなる。
下記例ではPydanticオブジェクトのクラス変数名がレスポンスの鍵になるので英語になってしまう。もちろん日本語を変数名に使用することはできない。

from pydantic import BaseModel, Field

class JP2ENG(BaseModel):
    message: str = Field(...)


@app.get("/jp", response_model=JP2ENG)
def jp():
    return {"message": "hello"} # JP#ENGクラスに変換され型チェックとキャストをしてくれる。

どうするか

Field()オブジェクトのalias機能を使用する。

class JP2ENG(BaseModel):
    message: str = Field(..., alias="こんにちは")


@app.get("/jp", response_model=JP2ENG)
def jp():
    return {"こんにちは": "hello"}

こうすることでPydanticの機能を維持しつつ日本語を返すことができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0