• FastAPI学习2.url 上的路径参数 上海


    前言

    在开发restful接口的时候,会遇到接口路径带参数的情况,比如

    • 查询单个 book 接口:get /api/v1/book/{id}
    • 修改单个 book 接口:put /api/v1/book/{id}
    • 删除单个 book 接口: delete /api/v1/book/{id}

    这里路径里面的 {id} 就是路径参数

    简单示例

    可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量

    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id):
        return {"item_id": item_id}
    

    路径参数 item_id 的值将作为参数 item_id 传递给你的函数。

    启动服务后,在浏览器输入http://localhost:8000/items/11 ,会看到返回 {"item_id":"11"}

    如果你运行示例并访问 http://127.0.0.1:8000/items/foo,将会看到如下响应:{"item_id":"foo"}

    有类型的路径参数

    如果我们想让路径参数 item_id 只能传 数字类型,于是可以使用标准的 Python 类型标注为函数中的路径参数声明类型。

    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int):
        return {"item_id": item_id}
    

    在这个例子中,item_id 被声明为 int 类型。

    运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应:

    {"item_id":3}
    

    注意函数接收(并返回)的值为 3,是一个 Python int 值,而不是字符串 "3"。

    数据校验

    但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误:

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

    因为路径参数 item_id 传入的值为 "foo",它不是一个 int。
    如果你提供的是 float 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2
    所以,通过同样的 Python 类型声明,FastAPI 提供了数据校验功能。所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。

    docs文档

    打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档:

    顺序很重要

    在创建路径操作时,你会发现有些情况下路径是固定的。
    比如 /users/me,我们假设它用来获取关于当前用户的数据.
    然后,你还可以使用路径 /users/{user_id} 来通过用户 ID 获取关于特定用户的数据。
    由于路径操作是按顺序依次运行的,你需要确保路径 /users/me 声明在路径 /users/{user_id}之前:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/users/me")
    async def read_user_me():
        return {"user_id": "the current user"}
    
    
    @app.get("/users/{user_id}")
    async def read_user(user_id: str):
        return {"user_id": user_id}
    

    否则,/users/{user_id} 的路径还将与 /users/me 相匹配,"认为"自己正在接收一个值为 "me" 的 user_id 参数。

  • 相关阅读:
    sopt:一个简单的python最优化库
    条件GAN论文简单解读
    python PIL 图像处理库简介(一)
    python自动制作gif并添加文字
    github+hexo搭建博客
    haskell简明入门(一)
    DCGAN 代码简单解读
    手机浏览器 H5直播
    js获取网页的宽高
    vue 对象赋值 对象身上已经有了属性,但是视图层并没有更新该数据 问题
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15947854.html
Copyright © 2020-2023  润新知