本机上是社区版本pycharm,创建项目时无法直接选择fastapi框架,于是先创建一个项目(解释器用虚拟环境),然后再安装fastapi和uvicorn(运行服务器)
创建项目后,先激活虚拟环境:
.\.venv\Scripts\activate
激活后安装fastapi,uvicorn
pip install fastapi uvicorn
示例代码:
from fastapi import FastAPI
app = FastAPI() #创建FastAPI实例
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def hello(name: str):
return {"message": f"Hello {name}"}
@app.get("/age/{num}")
async def get_age(num:int): # 这个接口可用来体验自动类型校验
# 访问http://127.0.0.1:8000/age/zhang
#{"detail":[{"type":"int_parsing","loc":["path","num"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"zhang"}]}
return {"age": num}
访问fastapi交互式文档: http://127.0.0.1:8000/docs
路由:
url地址和处理函数之间的映射关系,它决定了当用户访问某个特定网址时,服务器应该执行哪段代码来返回结果。FastAPI的路由定义基于Python的装饰器模式
浏览器默认只能发get请求,因此get可以直接使用url访问,而post则要通过前端调用或者在Swagger UI测试。
参数:
同一段接口逻辑,根据参数不同返回不同的数据。参数就是客户端发送请求时附带的额外信息和指令,参数的作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互。
参数分类:
路径参数eg:
@app.get("/book/{id}")
async def get_book(id:int):
return {"book_id:": id,
"title": f"这是第{id}本书"}
路径参数————类型注解Path:
FastAPI允许为参数声明额外的信息和校验,先导入FastAPI的Path函数:
from fastapi import Path
@app.get("/book/{id}")
async def get_book(id:int = Path(...,gt=0,lt=101,description="书籍id,取值范围1-100")):
#路径参数,Path里的...必须写;description是在接口文档里(/docs)显示的,不是给用户看的
return {"book_id:": id,
"title": f"这是第{id}本书"}
@app.get("/author/{name}")
async def get_name(name:str = Path(...,min_length =2,max_length =10,description="作家姓名")):
return f"作者姓名是{name}"
查询参数:
声明的参数更不是路径参数时,路径操作函数会把该参数自动解释为查询参数
Query,使用前也要先导入:
from fastapi import Path,Query
@app.get("/news/news_list")
async def get_news_list(skip:int=Query(0,description="跳过的记录数",lt=100),limit:int = 10):
#这里的0是给skip指定的默认值
return {"skip": skip,
"limit": limit
}
#示例访问地址:
#http://127.0.0.1:8000/news/news_list?limit=10
#http://127.0.0.1:8000/news/news_list?skip=5&limit=10
Path路径参数与Query查询参数:
Path路径参数 精准定位单条资源->对应where id = ?
Query查询参数 条件筛选/模糊搜索/分页->对应where like、范围、多条件、limit。Query参数支持默认值,不传也没事,而Path路径参数必须传,没有默认。
请求体参数:
只是查询、看数据、不用改东西: 用GET+Path/Query;
要提交、保存、修改、数据敏感、数据复杂: 用POST+请求体参数。
pydantic作用:
自动校验前端传过来的数据对不对,少传报错,传错类型报错;定义请求体格式,告诉前端传什么,把前端传的json自动转成对象(如前端传入姓名与密码,我可以直接user.username,user.password访问)
同样要先安装pydantic并导入BaseModel
from pydantic import BaseModel
#定义类型(要post什么)告诉前端要传什么
class User(BaseModel):
username:str
password:str
@app.post("/register")
async def register(user: User):# 这里指明要post的类型,这个user就是请求体参数
return{
"code": 200,
"msg": "注册成功",
"username": user.username
}