准备工作
- python3.7以上, fastapi(pip install fastapi)
第一个python应用
- 需要pip install uvicorn
- 新建文件index.py
import uvicorn
from fastapi import Body, FastAPI, Header
app = FastAPI()
@app.get('/')
def index():
return 'hello world'
if __name__ == '__main__':
uvicorn.run(app)
get请求
@app.get('/')
def index():
return 'hello world'
post请求
@app.post('/login')
def login():
return {'msg': 'login success'}
同时可以用多种方法请求
@app.api_route('/all_methods', methods=('GET', 'POST'))
def all_methods():
return {'msg': '支持get 和post 两种方法'}
get 传参
@app.get('/id/{id}')
def getId(id):
return {'id': id}
post 传参
@app.post('/getBody')
def getBody(data=Body(None)):
return {'data': data}