【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
あわせて読みたい
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ドキュメントがあります。 このドキュメントはタグで分類したり、任意の説明文章を追加することが簡単にできますのでご紹介い…

descriptionmedia_typeexample value
等が変化しています。控え目に言って最強ですね。
FastAPIの基礎についての記事まとめ

コメント