实现一个RESTful API

RESTful API(Representational State Transfer)是一种基于HTTP协议的软件架构风格,它定义了客户端如何与服务器进行交互,以及服务器应如何响应客户端的请求。

RESTful API的设计理念是,客户端和服务器之间通过HTTP协议通信,服务器提供资源,客户端通过资源的URL来获取资源。

在本文中,我们将使用FastAPI来实现一个RESTful API。

1 安装FastAPI

首先,你需要安装FastAPI。你可以通过以下命令安装:

1
pip install fastapi

2 编写代码

接下来,我们编写一个简单的RESTful API。

2.1 . 定义一个路由(接口1)

我们定义一个GET请求的路由,路径为’/‘,用于处理根路径的请求。

1
2
3
4
5
6
7
8
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def root():
res = {"message": "Welcome to the root path!"}
return res

在这个脚本中@app.get('/')是一个python装饰器,装饰器定义了一个GET请求的路由,路径为’/‘。也就是说,当客户端向服务器发送GET请求到路径’/‘时,服务器将调用root()函数来处理请求。也就是说,当客户端向服务器发送GET请求到路径’/‘时,服务器将返回一个JSON格式的字符串,其中包含一条欢迎信息。

2.2 . 定义一个计算两个整数和的路由(接口2)

我们定义一个GET请求的路由,路径为’/test/a={a}/b={b}’,用于计算两个整数的和。

1
2
3
4
5
6
7
8
9
from fastapi import FastAPI

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

前面说过,装饰器用于定义一个GET请求的路由,也就是说要使用这个接口,客户端需要发送GET请求到路径 /test/a={a}/b={b}, 相当于在浏览器中输入(如果主机地址为127.0.0.1:8080)http://127.0.0.1:8080/test/5/10来访问接口。

2.3 . 运行应用

最后,我们运行应用,监听所有网络接口,端口为8080,使用1个工作线程。

1
2
3
4
5
6
7
import uvicorn 

if __name__ == '__main__':
uvicorn.run(app=app,
host="0.0.0.0",
port=8080,
workers=1)

3 运行应用

运行应用,在命令行中输入:

1
uvicorn main:app --reload

这将启动FastAPI应用,监听所有网络接口,端口为8080,使用1个工作线程,并自动重载代码。

4 测试应用

你可以通过以下方式测试应用:

4.1 . 使用浏览器访问

你可以直接在浏览器中输入URL来访问接口。例如:

  • 访问根路径:http://127.0.0.1:8080/
  • 访问计算两个整数和的路径:http://127.0.0.1:8080/test/a=5/b=10

4.2 . 使用命令行工具(如curl

你可以在命令行中使用curl命令来发送HTTP请求。例如:

  • 访问根路径:

    1
    curl http://127.0.0.1:8080/

    这将返回:

    1
    {"message": "Welcome to the root path!"}
  • 访问计算两个整数和的路径:

    1
    curl http://127.0.0.1:8080/test/a=5/b=10

    这将返回:

    1
    {"res": 15}

4.3 . 使用Postman或类似的工具

Postman是一个流行的API测试工具,你可以使用它来发送HTTP请求并查看响应。

  1. 打开Postman。
  2. 创建一个新的GET请求。
  3. 输入URL,例如:
    • 根路径:http://127.0.0.1:8080/
    • 计算两个整数和的路径:http://127.0.0.1:8080/test/a=5/b=10
  4. 点击“Send”按钮,查看响应。

4.4 . 使用Python脚本

你也可以编写一个简单的Python脚本来发送HTTP请求。例如:

1
2
3
4
5
6
7
8
9
import requests

# 访问根路径
response = requests.get("http://127.0.0.1:8080/")
print(response.json()) # 输出: {'message': 'Welcome to the root path!'}

# 访问计算两个整数和的路径
response = requests.get("http://127.0.0.1:8080/test/a=5/b=10")
print(response.json()) # 输出: {'res': 15}

4.5 . 使用JavaScript(在浏览器中)

你可以在浏览器中使用JavaScript的fetch API来发送HTTP请求。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test FastAPI</title>
</head>
<body>
<script>
// 访问根路径
fetch('http://127.0.0.1:8080/')
.then(response => response.json())
.then(data => console.log(data)); // 输出: {message: 'Welcome to the root path!'}

// 访问计算两个整数和的路径
fetch('http://127.0.0.1:8080/test/a=5/b=10')
.then(response => response.json())
.then(data => console.log(data)); // 输出: {res: 15}
</script>
</body>
</html>