环境准备
安装python
这里我准备使用3.9版本的python进行学习,因为fast交互文档的原因,我将从原本使用的3.7版本升级到3.9版本,这里的原因稍后介绍

安装fastapi
pip install fastapi
安装ASGI 服务器
pip install "uvicorn[standard]"
uvicon介绍可查看:https://blog.csdn.net/m0_59236602/article/details/136281699
uvicon官网可查看:https://www.uvicorn.org/
创建main.py
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
运行
uvicorn main:app --reload

浏览器访问接口:

浏览器访问交互式文档:

访问交互式文档的时候就可能会出现无法访问的情况,实际这是访问必要的静态资源超时了

交互式文档因为需要使用swagger-ui-bundle.js、swagger-ui.css、redoc.standalone.js这几个静态资源文件,但是fastapi自带的是静态资源地址在国外,国内无法正常访问,因此需要进行额外的处理。
解决办法当然已经有大佬找到了,同时官方文档其实也给出了解决办法,但还是大佬的好用,站在巨人的肩膀上吧,可见:
大佬的python库:https://blog.csdn.net/jaket5219999/article/details/135003381
官方解决办法:https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/
因为我采用的是大佬封装好的库fastapi-cdn-host,这个库需要3.8以上才支持,因此就不得不将自己3.7版本的python升级了

最后试试效果:
pip install fastapi-cdn-host
from fastapi import FastAPI
import fastapi_cdn_host
app = FastAPI()
fastapi_cdn_host.patch_docs(app)
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
完美访问交互式文档


浙公网安备 33010602011771号