使用fastapi写一个http接口
程序员文章站
2024-03-18 22:46:16
...
一,使用工具:FastAPI和uvicorn
通常我们写一个简单的http接口时常用flask,这次用点不一样的。
FastAPI是一个快速(高性能)的Web框架,需Python 3.6以上,安装方法:pip install fastapi
uvicorn是一个基于asyncio开发的一个轻量级高效的web服务器框架。需python3.5.3以上,安装方法:pip install uvicorn
二,get接口
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/07/10 20:27
# @author : LanBingWa
# @function: get service of fastapi
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get('/test/a={a}/b={b}')
def calculate(a: int = None, b: int = None):
c = a + b
res = {"res": c}
return res
if __name__ == '__main__':
uvicorn.run(app=app,
host="0.0.0.0",
port=8080,
workers=1)
浏览器访问接口:http://127.0.0.1:8080/test/a=3/b=8
三,post接口
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/07/10 20:43
# @author : LanBingWa
# @function: post service of fastapi
from pydantic import BaseModel
from fastapi import FastAPI
import uvicorn
app = FastAPI()
class Item(BaseModel):
a: int = None
b: int = None
@app.post('/test')
def calculate(request_data: Item):
a = request_data.a
b = request_data.b
c = a + b
res = {"res": c}
return res
if __name__ == '__main__':
uvicorn.run(app=app,
host="0.0.0.0",
port=8080,
workers=1)
浏览器访问接口:http://127.0.0.1:8080/test
推荐阅读