FastApi入门

314 阅读1分钟

准备工作

  • 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}