本文最后更新于41 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com
1、pycharm创建项目
2、项目启动
#reload可以使得服务器项目自动重启来应对修改的代码
uvicorn main:app --reload
3、路由
Fastapi的路由定义基于Python的装饰器模

4、路径参数
from fastapi import FastAPI, Path, Query
#路径参数,Path参数验证
@app.get("/book/{id}")
async def get_book(id: int = Path(..., gt=0, lt=100, description="书籍编号,取值范围0-100")):
return {"id": id, "title": f"这是第{id}本书"}
5、查询参数
from fastapi import FastAPI, Path, Query
#查询参数:需求 查询新闻 分页,skip:跳过的记录数, limit:返回的记录数 10,用Query参数验证
@app.get("/news/news_list")
async def get_news_list(skip: int = Query(0., gt=0, lt=100, description="跳过的记录数"), limit: int = Query(10, description="返回的记录数")):
return {"skip": skip, "limit": limit}
6、请求体参数
from pydantic import BaseModel, Field
#请求体参数 #注册: 用户名、密码 str类型
#定义类型, 继承BaseModel,用Field定义字段属性
class UserRegister(BaseModel):
username: str = Field(default="张三", min_length=2, max_length=10, description="用户名,长度2-10")
password: str = Field(min_length=3, max_length=20, description="密码,长度6-20")
#写路由
@app.post("/register")
async def register(user: UserRegister):
return user
7、自定义响应体格式
# 自定义响应数据格式 需求 新闻接口 响应数据格式 id、title、content
class News(BaseModel):
id: int
title: str
content: str
@app.get("/news/{id}", response_model=News)
async def get_news(id: int):
return {
"id": id,
"title": f"这是第{id}条新闻",
"content": f"这是第{id}条新闻的内容"
}
8、异常处理
from fastapi import FastAPI, Path, Query, HTTPException
#异常处理(HTTPException) 需求 按照id查询新闻 1-6
@app.get("/news/{id}")
async def get_news(id: int):
id_list = [1, 2, 3, 4, 5, 6]
if id not in id_list:
raise HTTPException(status_code=404, detail="新闻不存在")
return {
"id": id
}

