· 约 3 分钟

11-FastAPI基础入门-响应类型-HTML格式

  • FastAPI
  • Python

学习目标

核心概念

代码示例

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get("/", response_class=HTMLResponse)
def home():
    html = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>FastAPI 首页</title>
        <style>
            body { font-family: Arial; margin: 40px; background: #f7f9fc; }
            .card { max-width: 600px; padding: 24px; border-radius: 12px; background: white; }
            h1 { color: #0f4c81; }
        </style>
    </head>
    <body>
        <div class="card">
            <h1>欢迎来到 FastAPI 课程案例</h1>
            <p>这个页面由 FastAPI 直接返回 HTML。</p>
            <p>后续我们会继续把接口、数据库和前端页面串起来。</p>
        </div>
    </body>
    </html>
    """
    return html

案例理解

易错点

我的补充