【FastAPI】カスタムレスポンスの追加やドキュメントの記述
当ページのリンクには広告が含まれています。

FastAPI
は、基本的にFastAPI
側でよしなに変換してJSON
形式で返してくれますが、別のレスポンスが必要な場合があります。例えば
- テキスト
- リスト
- html・xml
- ファイル
等が挙げられます。
今回はカスタムレスポンスの使い方をご紹介いたします。
FastAPIの基礎についての記事まとめ
目次
カスタムレスポンス
カスタムレスポンスを使用する場合にはfastapi.responses
のResponse
をインポートします。
また、Response
にはサブクラスが用意されており、専用のPlainTextResponse
やHTMLResponse
がなどがあります。
あわせて読みたい


レスポンスを直接返す – FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
あわせて読みたい


カスタムレスポンス – HTML、ストリーム、ファイル、その他のレスポンス – FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Response
from fastapi import APIRouter
from fastapi.responses import Response
router = APIRouter(
prefix='/products',
tags=['products']
)
products = ['water', 'cola', 'coffee']
@router.get('/all')
def get_products_all():
text_data = " ".join(products)
return Response(content=text_data, media_type='text/plain')
products
でデータとしてリストを作成しました。
Response(content=text_data, media_type='text/plain')
content
で返すデータを、media_type
で型指定しています。

ステータスコードの付与
ステータスコードの付与も簡単で、status_code
を記入するだけです。
from fastapi import status
~~~
Response(content=text_data, media_type='text/plain', status_code=status.HTTP_200_OK)
関連記事


【FastAPI】任意のhttpステータスコードを付与する【入門】
代表的なステータスコードには 成功(Success)の200未検出(Not Found)の404サーバーエラー(Internal Server Error)の500 等がありますが、レスポンスがどのような状態な…
HTMLResponse
HTML
も可能です。
関連記事


【FastAPI】テンプレートエンジンを使ってHTML・CSSを配信
FastAPIを使用してJSONではなく、テンプレートエンジンを用いてHTMLやCSSを返す方法をご紹介いたします。 この記事のサンプルコード テンプレートエンジン テンプレート…
from fastapi.responses import HTMLResponse
@router. get('/{id}')
def get_product(id: int):
product = products[id]
html = f"""
<html>
<h2>product is {id}</h2>
</html>
"""
return HTMLResponse(content=html, media_type="text/html", status_code=status.HTTP_200_OK)
また、response_class
にHTMLResponse
を指定することも可能です。
@router. get('/{id}', response_class=HTMLResponse)
def get_product(id: int):
product = products[id]
html = f"""
<html>
<h2>product is {id}</h2>
</html>
"""
return html

その他にもPlainTextResponse
やXmlResponse
などがあります。
ドキュメントへの記述
レスポンスを作成することは出来ましたが、このままだとドキュメントには何も記載が無く、レスポンス例もstring
しか記載されていません。
レスポンスに関しての記述を追加してみましょう。
あわせて読みたい


Additional Responses in OpenAPI – FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
@router.get('/{id}', responses={
200: {
"content": {
"text/html": {
"example": "<div>product is id</div>"
}
},
"description": "return html object"
}
})
def get_product(id: int):
product = products[id]
html = f"""
<html>
<h2>product is {id}</h2>
</html>
"""
return HTMLResponse(content=html, media_type="text/html", status_code=status.HTTP_200_OK)
responses
引数を追加し、status_code
・media_type
・例や説明を追加できます。
これらはステータスコード毎に記述可能です。
関連記事


【FastAPI】APIドキュメントに説明を追加する【入門】
FastAPIにはとても便利な自動生成されるAPIドキュメントがあります。 このドキュメントはタグで分類したり、任意の説明文章を追加することが簡単にできますのでご紹介い…

description
media_type
example value
等が変化しています。控え目に言って最強ですね。
FastAPIの基礎についての記事まとめ
コメント