通过创建 swagger UI 使用 FastAPI 访问 XML REST API

通过创建 swagger UI 使用 FastAPI 访问 XML REST API

要使用 FastAPI 为 XML Rest API 创建一个招摇的 UI,

我们采用了基于公共 xml 的公共 REST Api: http://www.dneonline.com/calculator.asmx

安装以下 pip 模块

要求
快速API
乌维康

安装后创建一个带有文件名的示例程序: main.py 如下所示以访问 api

主文件

导入请求
导入日志
从输入 import 可选
从输入导入联盟
从 fastapi 导入 FastAPI,响应

从枚举导入枚举

从 requests.packages.urllib3.exceptions 导入 InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

logging.basicConfig(filename="std.log", format='%(asctime)s %(levelname)s %(message)s', filemode='w')

记录器=记录.getLogger()

logger.setLevel(logging.DEBUG)

def getdata_dneonline(newurl, newfname, x, y):
尝试:
#url = "http://www.dneonline.com/calculator.asmx"
#f = open("addHelper.xml", "rt")
f = open(newfname, "rt")
有效载荷 = f.read()
f.close()
标题 = {
“内容类型”:“文本/xml”
}
response = requests.request("POST", newurl, headers=headers, data=payload.format(a=x,b=y))
logger.debug(response.text)
返回响应.文本
例外为 e:
打印(“错误:”,e)

untangle.parse(getdata_dneonline("http://www.dneonline.com/calculator.asmx", "addHelper.xml"))

应用程序 = FastAPI()

@app.get('/addition')
异步定义计算器_add(inputA:int,inputB:int):
#return getdata_dneonline("http://www.dneonline.com/calculator.asmx", "addHelper.xml")
返回响应(内容=getdata_dneonline(“ http://www.dneonline.com/calculator.asmx ”,“addHelpers.xml”,inputA,inputB),media_type="application/xml")

@app.get('/减法')
异步defcalculator_sub(inputA:int,inputB:int):
#return getdata_dneonline("http://www.dneonline.com/calculator.asmx", "addHelper.xml")
返回响应(内容=getdata_dneonline(“ http://www.dneonline.com/calculator.asmx ”,“subHelpers.xml”,inputA,inputB),media_type =“application/xml”)

@app.get('/乘')
异步defcalculator_multiply(inputA:int,inputB:int):
#return getdata_dneonline("http://www.dneonline.com/calculator.asmx", "addHelper.xml")
返回响应(内容=getdata_dneonline(“ http://www.dneonline.com/calculator.asmx ”,“multipleHelpers.xml”,inputA,inputB),media_type =“application/xml”)

@app.get('/分区')
异步定义计算器_除法(输入A:整数,输入B:整数):
#return getdata_dneonline("http://www.dneonline.com/calculator.asmx", "addHelper.xml")
返回响应(内容=getdata_dneonline(“ http://www.dneonline.com/calculator.asmx ”,“divideHelpers.xml”,inputA,inputB),media_type =“application/xml”)

要启动程序,请执行以下命令

uvicorn main:app --reload

发布启动服务,访问 url https://127.0.0.1:8000/docs ,它会像吹气一样打开招摇的用户界面

你可以像下面这样玩公共休息 api

您可以从我的 github 获取示例代码: https://github.com/hemanth22/python-restapi/tree/feature/logger

如果你喜欢这个博客,请点赞和评论和分享。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明

本文链接:https://www.qanswer.top/29408/15501201

posted @ 2022-09-12 01:16  哈哈哈来了啊啊啊  阅读(219)  评论(0)    收藏  举报