使用 FastAPI 构建现代化的高性能 Web API

原文链接:mp.weixin.qq.com/s/PJhqLRiZl...

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API。它基于 Python 3.6+ 类型提示,旨在提供快速开发、简洁设计和高性能。本文将引导你了解 FastAPI 的基础知识,包括环境搭建、基本概念、路由创建、请求处理,以及响应格式化等,提供一个全面的入门指南。

FastAPI 概述

FastAPI 是一个用于构建 API 的现代 Python Web 框架。它兼容 OpenAPI 和 JSON Schema,提供了自动数据验证、序列化和 API 文档等功能。

核心特点

  • 高性能:与 NodeJS 和 Go 相当。
  • 快速编码:减少约 40% 的开发时间。
  • 自动生成文档:支持 Swagger UI 和 ReDoc。
  • 基于标准:基于 OpenAPI 和 JSON Schema。

环境搭建

首先,需要安装 FastAPI 和一个 ASGI 服务器,如 Uvicorn。

bash 复制代码
pip install fastapi[all]

创建第一个 FastAPI 应用

基本示例

创建一个基本的 FastAPI 应用:

python 复制代码
from fastapi import FastAPI

app = FastAPI()

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

运行应用

使用 Uvicorn 运行应用:

bash 复制代码
uvicorn main:app --reload

访问 http://127.0.0.1:8000 可以看到响应。

路由和参数

FastAPI 使用 Python 类型提示定义路径参数和查询参数。

路径参数示例

python 复制代码
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

查询参数示例

python 复制代码
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

请求体和数据模型

FastAPI 使用 Pydantic 库来处理数据模型。

请求体定义

python 复制代码
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
async def create_item(item: Item):
    return item

响应处理

FastAPI 允许你定义响应模型和状态码。

响应模型

python 复制代码
from fastapi.responses import JSONResponse

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    ...
    return JSONResponse(content=item)

异常处理

FastAPI 提供了异常处理机制。

python 复制代码
from fastapi import HTTPException

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]

中间件和依赖注入

FastAPI 支持中间件和依赖注入,以增强应用功能。

python 复制代码
from fastapi import Depends

def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

部署

FastAPI 应用可以部署在多种服务器和平台上,如 Gunicorn、Docker 等。

使用 Gunicorn 部署

bash 复制代码
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app

总结

FastAPI 以其高性能、快速开发和易用性在 Python Web 框架中脱颖而出。通过本文的介绍,你应该能够掌握 FastAPI 的基本用法,并开始构建自己的 Web API。随着学习的深入,你还可以探索 FastAPI 更多高级功能,以构建更复杂和强大的应用。

相关推荐
APIshop35 分钟前
阿里巴巴中国站按图搜索1688商品(拍立淘)API 返回值说明
java·python·图搜索算法
哈库纳玛塔塔39 分钟前
dbVisitor 利用 queryForPairs 让键值查询一步到位
java·数据库·python
sa1002741 分钟前
京东评论接口调用、签名生成与异常处理
开发语言·数据库·python
赵谨言1 小时前
基于Python实现地理空间数据批处理技术探讨及实现--以“多规合一“总体规划数据空间叠加分析为例
大数据·开发语言·经验分享·python
DN20201 小时前
AI销售:从不迟到早退,永远秒回,您的忠实员工
人工智能·python
编程之升级打怪2 小时前
Python的图形框架tkinter使用案例
python
liu****2 小时前
3.RNN及其变体
人工智能·python·rnn·深度学习
大江东去浪淘尽千古风流人物3 小时前
【Sensor】IMU传感器选型车轨级 VS 消费级
人工智能·python·算法·机器学习·机器人
码农小韩4 小时前
AIAgent应用开发——DeepSeek分析(一)
人工智能·python·深度学习·agent·强化学习
学Linux的语莫4 小时前
skills的使用
java·数据库·python