目录
前言
利用python fastAPI框架搭建简便的api服务
一、fastAPI是什么?
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。总之它可以简单快捷的创建api服务。
二、安装
1.fastapi的安装(此处用的是阿里云镜像源)
pip install fastapi -i https://mirrors.aliyun.com/pypi/simple
pip install uvicorn -i https://mirrors.aliyun.com/pypi/simple
2.测试一下
创建文件test.py,代码如下:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def main():
return {"message": "hello"}
然后打开终端(wins + R)启动uvicorn服务:
uvicorn test:app --reload
# 指定端口启动
uvicorn test:app --host '0.0.0.0' --port 8000 --reload
其中test 为文件名;app为test.py中创建的app对象;–reload为热启动,重启服务
看到如图结果代表启动成功。打开游览器输入127.0.0.1:8000/
即可看到main方法中的输出结果。
三、使用
1.声明路径参数
from fastapi import FastAPI
app = FastAPI()
@app.get('/home/{key}')
def main(key): # 这里可以标记key的类型,例如: def main(key: int)
return {"key": key}
请求结果:
2. 声明路径参数有效值
from fastapi import FastAPI
from enum import Enum
app = FastAPI()
class limit(str, Enum):
value1 = "111"
value2 = "222"
value3 = "333"
@app.get('/home/{key}')
def main(key: limit):
return {"key": key}
超出限制范围的请求会返回告知你一个错误信息的json:
3. 声明路径参数为路径
from fastapi import FastAPI
app = FastAPI()
@app.get('/file/{file_path:file_path}')
def main(file_path):
return {"path": file_path}
4. 声明params参数
from fastapi import FastAPI
app = FastAPI()
@app.get('/file')
def main(value1, value2):
return {"value1": value1, "value2": value2}
使用浏览器访问http://127.0.0.1:8000/file?value1=ssss&value2=rrrrrrr
,你会得到:{ "value1": "ssss", "value2": "rrrrrrr" }
5. 请求体(如post请求会用到)
定义请求体,需要使用 Pydantic
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.get('/home')
def main(item: Item):
return item
class Item(BaseModel):
value1: str
value2: str = None
value3: float = None
用postman发送模拟post请求(请求体格式为json):