第一步:导入FastAPI
from fastapi import FastAPI #导入FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
FastAPI是继承了Starlette的类
FastAPI可以调用Starlette的所有功能
第二步:创建FastAPI实例
from fastapi import FastAPI app = FastAPI() #创建FastAPI实例 @app.get("/") async def root(): return {"message": "Hello World"}
变量app是FastAPI的类实例,该实例是创建API的主要交互对象。
第三步:创建路径操作
路径是指URL的第一个反斜杠(/)及之后的内容。
https://example.com/items/foo
/items/foo 表示路径或路由或端点
操作是指HTTP方法,常用的方法如下:
- POST :创建数据
- GET :读取数据
- PUT :更新数据
- DELETE :删除数据
@app.get("/")告诉FastAPI下方函数以如下方式处理访问请求:
- 请求路径为
/
- 使用
get
操作
@app 语法是python装饰器
装饰器接收到下方函数,并用它执行一些操作,
本例中,这个装饰器告诉FastAPI下方函数对应的路径是 / 和 get 操作,这就是路径操作装饰器。
第四步:定义路径操作和函数
路径操作函数由以下几部分组成:
- 路径:
/
- 操作:
get
- 函数: 装饰器下方的函数
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
FastAPI每次接收使用get方法访问URL /
的请求时都会调用这个函数。本例中的路径操作函数是异步函数(async)
也可以不使用异步函数,例如:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}
第五步:返回内容
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
路径操作函数可以返回字典、列表以及字符串、整数等单值。
还可以返回Pydantic模型