为什么选择 FastAPI?

FastAPI 入门

Matt Eckerle

Software and Data Engineering Leader

什么是 FastAPI?

先看一些术语

  1. API:应用程序编程接口——指使用 HTTP 协议传输结构化数据的 Web 应用
  2. Web 应用:通过网络提供服务的应用
  3. Web 框架:用于构建 Web 应用的软件框架

FastAPI 用 Python 快速构建高性能 API

FastAPI 入门

FastAPI 关键特性

  • 快速: 性能极高
  • “低代码”,易上手: Python 注解与类型提示
  • 健壮: 生产可用,内置自动文档
  • 基于标准: 基于 OpenAPI 与 JSON Schema

FastAPI 标志

OpenAPI 标志

JSON 标志

1 https://fastapi.tiangolo.com/
FastAPI 入门

FastAPI 与其他 Python Web 框架对比

Flask

  • 构建基于 Web 的(GUI)应用
  • ORM 可选

FastAPI

  • 构建 API
  • ORM 可选

Django

  • 构建基于 Web 的(GUI)应用
  • 内置 ORM

主要差异

  • 适用于无数据库操作的 API
  • 数据与机器学习事务
FastAPI 入门

用 FastAPI 构建第一个 Web 应用

1. 安装 FastAPI

pip install fastapi

2. 在 main.py 中创建应用

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello World"}

3. 运行服务器

fastapi dev main.py

REPL 显示 FastAPI 正在运行

FastAPI 入门

开始练习 FastAPI 之前

注意事项

  1. 无法用“运行此代码”按钮启动 FastAPI 服务器
  2. 请在 Python 编辑器中将服务器代码保存为 main.py

  3. 在终端运行命令 fastapi dev main.py

  4. 在终端日志中确认显示 Application startup complete.
  5. 在同一终端按 Control + C 停止实时服务器
  6. 建议在您自己的 Python 环境中安装 FastAPI,以便熟练练习
FastAPI 入门

Ayo berlatih!

FastAPI 入门

Preparing Video For Download...