在当前目录创建文件夹 test,并创建三个文件 fapi.py、test/t1.py、test/__init__.py。目录结构如下
.
├── fapi.py
└── test
├── __init__.py
└── t1.py
主文件 fapi.py
# -*- coding: utf-8 -*-
from fastapi import FastAPI
from fastapi import APIRouter
import uvicorn
from test import t1
api_router = APIRouter()
api_router.include_router(t1.test_router, prefix="/test", tags=["CCCCCCCCCCCCCCCCC"] )
def create_app():
tags_metadata = [{ "name": "测试APIII", "description": "fastapi 练习" }]
# 创建api应用
app = FastAPI( title="测试API", description="learnlearn", version="1.0", docs_url="/docs", openapi_url="/api/api.json", openapi_tags=tags_metadata)
# 增加路由
app.include_router( api_router, prefix="/tt")
return app
# 创建一个应用
testapp = create_app()
if __name__ == "__main__":
uvicorn.run(app='fapi:testapp', host="0.0.0.0", port=3456, reload=True)
在test目录下创建 t1.py 文件
# -*- coding: utf-8 -*-
from fastapi import status
from fastapi import APIRouter
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel
from fastapi import Body
# 创建路由
test_router = APIRouter()
# get请求处理
@test_router.get("/t1", summary=u"第一个测试")
def t1( a: str = "<not given>", b: str = "<not given>") -> Response :
pstr = "param a is ["+a+"]; param b is ["+b+"]"
return JSONResponse(
status_code=status.HTTP_200_OK,
content = {
"code": "1001",
"message": "hello , first fast api return",
"params" : pstr
})
class Item(BaseModel):
aa: str = "<not given>"
bb: str = "<not given>"
# post请求
@test_router.post("/t1", summary=u"第一个测试")
def t1_post(item: Item = Body(...)) -> Response :
datastr = "param a is ["+item.aa+"]; param b is ["+item.bb+"]"
return JSONResponse(
status_code=status.HTTP_200_OK,
content = {
"code": "1002",
"message": "hello , first fast api return",
"datastr": datastr
})
在test目录下创建空文件 __init__.py
# -*- coding: utf-8 -*-
启动api接口

接口 可以通过访问 http://xx.xx.xx.xx:3456/docs 查看

请求接口GET

请求接口POST

发表回复