艾克斯记事

FastAPI 获取URL路径做为参数使用

可以使用格式化字符串来传递URL中的参数,使用起来非常方便;

from fastapi import FastAPI

app = FastAPI()

@app.get("/Test/{query_key}")
def FastTest(query_key):
  return {"msg":query_key}

访问路径: http://127.0.0.1:8000/Test/abc888

返回结果:

{"msg":"abc888"}

也可以为参数设置一个类型:

from fastapi import FastAPI

app = FastAPI()

@app.get("/Test/{query_key}")
def FastTest(query_key: int):
  return {"msg":query_key}

这时候如果用同样的路径就报错了(包含字符的路径):

{"detail":[{"loc":["path","query_key"],"msg":"value is not a valid integer","type":"type_error.integer"}]}