FastApi入门

第一个fastapi程序

python 复制代码
from fastapi import FastAPI
app = FastAPI()


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


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

路由

fastapi的路由定义基于python的装饰器模式

python 复制代码
@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

同一个接口参数不同,可以返回不同的数据

参数分类

路径参数--类型注解Path

fastapi允许为参数声明额外信息和校验

1.导入Path函数

path函数常用的参数

python 复制代码
@app.get("/book/{id}")
async def get_book(id: int = Path(..., gt=0, le=100, description="The id of the book to get")):
    return {"id": id,"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}

查询参数--url?之后的参数

python 复制代码
@app.get("/book/news_list")
async def get_book_list(id: int = Query(..., gt=0, le=100, description="The id of the book to get")):
    return {
        "id": id,
        "title": "The Great Gatsby",
        "author": "F. Scott Fitzgerald"
    }

请求体参数

HTTP的一个请求包含三部分

1.请求行

包含方法,url,协议版本

2.请求头

元数据信息(Content-Type,Authorization等)

3.请求体

实际要发送的数据内容

具体使用步骤

1.定义类型

python 复制代码
from pydantic import BaseModel

#BaseModel的作用是接受HTTP请求中的json格式的参数,并将其转换成User类型
class User(BaseModel):
   username: str
   password: str

2.类型注解

python 复制代码
@app.post("/register")
async def register(user: User):
   return user

类型注解Field

导入pydantic的Field函数

python 复制代码
from pydantic import BaseModel,Field

class User(BaseModel):
    username: str = Field(default="张三",min_length=2,max_length=10,description="用户名,要求2-10个字符")
    password: str = Field(min_length=3,max_length=20)

Field常见的参数

请求体的作用是什么?

创建更新资源,比如注册需要添加用户数据

如何为请求体参数添加类型注解

使用py原生的Field注解

响应类型

默认情况下,FastApi会自动将路径操作函数返回的Py对象,经jsonable_encode转换为Json格式,并包装为JSONresponse返回

其他类型,

相应类型的设置方式

1.装饰器指定相应类型

场景:固定返回类型

python 复制代码
from fastapi.response import HTMLResponse

#返回相应HTML代码
@app.get("/html",response_class = HTMLResponse)
async def get_html():
     return "<h1>Hello<h1>"

2.返回响应类对象

场景:文件下载,图片,流式相应

python 复制代码
from fastapi import FastApi

@app.get("/file")
async def get_file():
    path = "./files/1.jpg"
    return FileRespnose(path)

3.自定义相应数据各式

可以用来约束相应的数据类型

python 复制代码
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":"这是一本书",
    "content":"小猪佩奇"
}

异常处理

对于客户端引发的错误,应使用fastapi.HTTPException来中断正常处理流程,并返回标准错误相应

python 复制代码
from fastapi improt FastApi,HTTPException

@app.get("/news/{id}")
async def get_news(id: int):
   id_list = [1,2,3,4,5]
   if id not in id_list:
     raise HTTPException(status_code=404,detail="当前id不存在")
   return {"id":id}