
- FastAPI 教程
- FastAPI - 首页
- FastAPI - 简介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 类型提示
- FastAPI - IDE 支持
- FastAPI - REST 架构
- FastAPI - 路径参数
- FastAPI - 查询参数
- FastAPI - 参数验证
- FastAPI - Pydantic
- FastAPI - 请求体
- FastAPI - 模板
- FastAPI - 静态文件
- FastAPI - HTML 表单模板
- FastAPI - 访问表单数据
- FastAPI - 上传文件
- FastAPI - Cookie 参数
- FastAPI - Header 参数
- FastAPI - 响应模型
- FastAPI - 嵌套模型
- FastAPI - 依赖项
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 数据库
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - Websockets
- FastAPI - FastAPI 事件处理器
- FastAPI - 挂载子应用
- FastAPI - 中间件
- FastAPI - 挂载 Flask 应用
- FastAPI - 部署
- FastAPI 有用资源
- FastAPI - 快速指南
- FastAPI - 有用资源
- FastAPI - 讨论
FastAPI - Hello World
入门
创建 FastAPI 应用的第一步是声明 FastAPI 类的应用程序对象。
from fastapi import FastAPI app = FastAPI()
这个 app 对象是应用程序与客户端浏览器交互的主要点。uvicorn 服务器使用此对象来监听客户端的请求。
下一步是创建路径操作。路径是客户端访问时会调用映射 URL 的 URL,与 HTTP 方法之一相关联的函数将被执行。我们需要将视图函数绑定到 URL 和相应的 HTTP 方法。例如,index() 函数对应于‘/’ 路径和‘get’ 操作。
@app.get("/") async def root(): return {"message": "Hello World"}
该函数返回 JSON 响应,但是,它也可以返回dict、list、str、int 等。它还可以返回 Pydantic 模型。
将以下代码保存为 main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def index(): return {"message": "Hello World"}
通过提及实例化 FastAPI 应用程序对象的文件来启动 uvicorn 服务器。
uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [28720] INFO: Started server process [28722] INFO: Waiting for application startup. INFO: Application startup complete.
打开浏览器并访问 https://127.0.0.1:/8000。您将在浏览器窗口中看到 JSON 响应。

广告