文章目录
- 1、安装
- 2、api实现
- 2.1、 ```app.get("/1")```
- 2.2、```app.get("/{a}")```
- 2.3、```@app.get("/{a}+{b}")```
- 2.4、函数和api分离
- 3、运行
原文链接:https://wangguo.site/posts/d98bb3c9.html
fastapi 是一个基于 Python 的 API 构建框架,简单且易用!
1、安装
安装,主要分为两部分:
1)fastapi:pip install fastapi
2)uvicorn:pip install uvicorn。服务器端,可以用来运行fastapi的代码。
也可以一起安装pip install fastapi[all]
2、api实现
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/1")
def read_root():
return ("hello")
2.1、 app.get("/1")
api路径引入,也就是用 1 调用 read_root函数,最终返回一个 hello。

2.2、app.get("/{a}")
@app.get("/{a}")
def read_root(a:int):
return ("hello")
也可以输入值,当输入一个int型参数,调用 read_root函数,返回一个 hello。

2.3、@app.get("/{a}+{b}")
@app.get("/{a}+{b}")
def read_root(a:int,b:int):
return (a+b)
实现一个a+b的API。

2.4、函数和api分离
不可能把所有的api函数都放在一个.py文件中,在python文件中可以通过import调用函数。
sum.py,定义了一个add函数,实现a+b
def add(a,b):
print(a+b)
return a+b
main.py,调用add函数
from typing import Union
from fastapi import FastAPI
from num import add
app = FastAPI()
@app.get("/{a}+{b}")
def read_root(a:int,b:int):
return add(a,b)

3、运行
uvicorn main:app --reload
ok,结束!
![C国演义 [第八章]](https://img-blog.csdnimg.cn/14fc0ae144a6447b9167929d023e6fbf.png)


















