API接口(1)
HTTP通信过程
这是一条绝对URI(统一资源标识符)的标准格式:
http://user:pass@www.example.com:80/dir/index.htm?uid=1#ch1user:pass:用户认证信息;/dir/index.htm:文件路径;uid=1:查询字符串;ch1:片段标识符
URL(统一资源定位器)是其中的一部分,它定义了重要的请求类型和资源路径,下面以GET类型请求和响应为例:
# 请求
GET /dir/index.htm HTTP/1.1
Host: www.example.com
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 16# 响应
HTTP/1.1 200 OK
Date: Tue, 10 Jul 2012 06:50:15 GMT
Content-Length: 362
Content-Type: text/html
<html>
...
JSON、Dict
JSON与字典都是键值对组成,JSON中键只能是字符或字符串,字典的键必须是可哈希(不可变,即对应的内存地址唯一)的对象,如:字符串、数字、元组,目的是为了高效查询,时间复杂度O(1)
router_table = {
("GET", "/api/users"): get_all_users_function,
("POST", "/api/users"): create_user_function,
("GET", "/api/articles"): get_articles_function
}FastAPI
成熟的API框架内部都是先通过正则表达式解析HTTP的请求报文,根据请求类型和资源路径调用后端函数,常见与数据库交互;然后将函数返回值以JSON格式返回,回填进响应报文发送给客户端。以FastAPI为例:
app = FastAPI()
@app.get("/api/users")
def get_all_users():
...
result = [{"id": row[0], "name": row[1], "role": row[2]} for row in rows]
return result
💬 评论区