FastAPI常见返回数据格式、数据类型总结
在 FastAPI 中,除了常见的 JSON 格式数据,还可以返回多种类型的数据,包括 HTML、纯文本、PDF、Markdown、图片等。
以下是常见的响应格式及其对应的代码示例:
1. JSON 格式
FastAPI 默认返回 JSON 格式的数据。你也可以使用 JSONResponse 来返回 JSON 数据。
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.get("/json") def get_json(): return JSONResponse(content={"message": "Hello, World!"})
2. HTML 格式
使用 HTMLResponse 可以返回 HTML 内容。
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/html", response_class=HTMLResponse) def get_html(): return """ <html> <head> <title>FastAPI HTML Response</title> </head> <body> <h1>Hello, HTML!</h1> </body> </html> """
3. 纯文本 (Plain Text) 格式
使用 PlainTextResponse 返回纯文本。
from fastapi import FastAPI from fastapi.responses import PlainTextResponse app = FastAPI() @app.get("/text", response_class=PlainTextResponse) def get_text(): return "Hello, Plain Text!"
4. Markdown 格式
使用 MarkdownResponse 返回 Markdown 格式的数据。
from fastapi import FastAPI from fastapi.responses import HTMLResponse import markdown app = FastAPI() @app.get("/markdown", response_class=HTMLResponse) def get_markdown(): markdown_text = "# Hello, Markdown\nThis is some text in **Markdown**." return HTMLResponse(content=markdown.markdown(markdown_text))
注意: MarkdownResponse 不直接存在,可以先用 markdown 库将 Markdown 转换为 HTML,然后使用 HTMLResponse 来返回。
5. PDF 格式
使用 FileResponse 返回 PDF 文件。
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/pdf", response_class=FileResponse) def get_pdf(): pdf_path = "/path/to/your/file.pdf" return FileResponse(pdf_path, media_type='application/pdf', filename="your_file.pdf")
6. 图片格式 (Image)
使用 FileResponse 返回图片文件,例如 PNG 或 JPG 格式。
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/image", response_class=FileResponse) def get_image(): image_path = "/path/to/your/image.png" return FileResponse(image_path, media_type='image/png', filename="image.png")
7. 文件下载 (任何文件)
使用 FileResponse 返回任意文件类型,用户可以下载。
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/download") def download_file(): file_path = "/path/to/your/file.zip" return FileResponse(file_path, media_type='application/octet-stream', filename="file.zip")
8. 流式响应 (Streaming Response)
使用 StreamingResponse 返回流式数据,如大文件或音频、视频等。
from fastapi import FastAPI from fastapi.responses import StreamingResponse from io import BytesIO app = FastAPI() def fake_video_stream(): for i in range(10): yield f"Streamed line {i}\n" @app.get("/stream") def stream_video(): return StreamingResponse(fake_video_stream(), media_type="text/plain")
9. 重定向 (Redirect Response)
使用 RedirectResponse 实现 URL 重定向。
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/redirect") def redirect_example(): return RedirectResponse(url="/json")
10. XML 格式
使用 Response 返回 XML 格式数据。
from fastapi import FastAPI, Response app = FastAPI() @app.get("/xml", response_class=Response) def get_xml(): xml_data = """ <note> <to>User</to> <from>FastAPI</from> <heading>Reminder</heading> <body>Don't forget to try XML!</body> </note> """ return Response(content=xml_data, media_type="application/xml")
11. CSV 格式
使用 Response 返回 CSV 格式数据。
from fastapi import FastAPI, Response app = FastAPI() @app.get("/csv", response_class=Response) def get_csv(): csv_data = "name,age\nAlice,30\nBob,25" return Response(content=csv_data, media_type="text/csv")
12. 二进制数据 (Binary Data)
使用 Response 返回二进制数据。
from fastapi import FastAPI, Response app = FastAPI() @app.get("/binary", response_class=Response) def get_binary(): binary_data = b"\x00\x01\x02\x03" return Response(content=binary_data, media_type="application/octet-stream")
总结
FastAPI 可以灵活返回多种数据格式,主要格式及对应的响应类如下:
- JSON:
JSONResponse - HTML:
HTMLResponse - 纯文本:
PlainTextResponse - PDF:
FileResponse - Markdown:
HTMLResponse(需要将 Markdown 转为 HTML) - 图片:
FileResponse - 文件下载:
FileResponse - 流式响应:
StreamingResponse - 重定向:
RedirectResponse - XML:
Response(手动定义media_type="application/xml") - CSV:
Response(手动定义media_type="text/csv") - 二进制数据:
Response(手动定义media_type="application/octet-stream")
所有media_type的类型总结如下
在 FastAPI 中,media_type 定义了 HTTP 响应的内容类型(即 Content-Type)。
这些内容类型可以用于指定返回的格式,常见的 media_type 类型基于 MIME(Multipurpose Internet Mail Extensions)标准。以下是常见的 media_type 类型列表:
1. JSON
application/json:表示 JSON 格式数据
media_type = "application/json"
2. HTML
text/html:表示 HTML 文档
media_type = "text/html"
3. 纯文本 (Plain Text)
text/plain:表示纯文本内容
media_type = "text/plain"
4. XML
application/xml或text/xml:表示 XML 文档
media_type = "application/xml" media_type = "text/xml"
5. CSV
text/csv:表示 CSV 格式的数据
media_type = "text/csv"
6. PDF
application/pdf:表示 PDF 文档
media_type = "application/pdf"
7. 图片 (Image)
-
image/png:表示 PNG 图片 -
image/jpeg:表示 JPEG 图片 -
image/gif:表示 GIF 图片 -
image/svg+xml:表示 SVG 图片
media_type = "image/png" media_type = "image/jpeg" media_type = "image/gif" media_type = "image/svg+xml"
8. 音频 (Audio)
-
audio/mpeg:表示 MP3 音频 -
audio/ogg:表示 OGG 音频 -
audio/wav:表示 WAV 音频
media_type = "audio/mpeg" media_type = "audio/ogg" media_type = "audio/wav"
9. 视频 (Video)
-
video/mp4:表示 MP4 视频 -
video/ogg:表示 OGG 视频 -
video/webm:表示 WebM 视频
media_type = "video/mp4" media_type = "video/ogg" media_type = "video/webm"
10. 二进制数据 (Binary Data)
application/octet-stream:表示通用的二进制数据流,常用于文件下载
media_type = "application/octet-stream"
11. Markdown
text/markdown:表示 Markdown 文档
media_type = "text/markdown"
12. JavaScript
application/javascript:表示 JavaScript 文件
media_type = "application/javascript"
13. CSS
text/css:表示 CSS 样式表
media_type = "text/css"
14. 表单数据 (Form Data)
-
application/x-www-form-urlencoded:表示 URL 编码的表单数据 -
multipart/form-data:表示带有文件的表单数据
media_type = "application/x-www-form-urlencoded" media_type = "multipart/form-data"
15. YAML
application/x-yaml或text/yaml:表示 YAML 格式数据
media_type = "application/x-yaml" media_type = "text/yaml"
16. ICO
image/x-icon:表示网站的 favicon 图标
media_type = "image/x-icon"
17. ZIP 文件
application/zip:表示 ZIP 压缩文件
media_type = "application/zip"
18. Excel 文件
-
application/vnd.ms-excel:表示 Excel 文件 (xls) -
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:表示 Excel 文件 (xlsx)
media_type = "application/vnd.ms-excel" media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
19. Rich Text Format (RTF)
application/rtf:表示 RTF 文本格式
media_type = "application/rtf"
20. ePub 格式
application/epub+zip:表示电子书的 ePub 格式
media_type = "application/epub+zip"
21. JSON-LD (JSON for Linked Data)
application/ld+json:表示 JSON-LD 格式,用于语义化网页内容
media_type = "application/ld+json"
22. OpenDocument 格式
-
application/vnd.oasis.opendocument.text:表示 OpenDocument 文本格式 (odt) -
application/vnd.oasis.opendocument.spreadsheet:表示 OpenDocument 表格格式 (ods)
media_type = "application/vnd.oasis.opendocument.text" media_type = "application/vnd.oasis.opendocument.spreadsheet"
总结
这些是 FastAPI 中常见的 media_type 类型,可以根据你的 API 返回的数据格式选择合适的 media_type。
你可以通过 Response 或特定的响应类(如 JSONResponse, HTMLResponse 等)来指定返回数据的 media_type,从而告诉客户端该如何处理响应内容。

浙公网安备 33010602011771号