当前位置: 首页 > news >正文

【碎片】FastAPI 路径参数

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于基于标准 Python 类型提示使用 Python 3.7+ 构建 API。它提供交互式 API 文档的自动生成,使您的 API 更容易理解和使用。在本博客中,我们将深入探讨 FastAPI 中请求处理和路径操作的基础知识,特别关注路径参数和查询参数。

什么是路径操作?

路径操作是应用程序中处理特定 HTTP 请求的端点。在 FastAPI 中,您可以使用映射到 HTTP 方法(GET、POST、PUT、DELETE)的装饰器来定义这些操作。每个路径操作都可以有自己的路径,其中可以包含路径参数。

路径参数

路径参数是嵌入在路径本身中的变量。这些参数允许您的 API 直接从 URL 捕获和使用动态值。

示例:路径参数

    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` 是路径参数。当您访问 `/items/42` 时,`item_id` 将为 `42`。

    查询参数

    查询参数是可选的,通常用于过滤或排序 API 返回的数据。它们添加到 URL 末尾,以 `?` 开头,后跟用 `&` 分隔的键值对。

    示例:查询参数

      from fastapi import FastAPI
      app = FastAPI()
      @app.get("/items/")async def read_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}

      此处,`skip` 和 `limit` 是查询参数。当您访问 `/items/?skip=5&limit=20` 时,`skip` 值将为 `5`,`limit` 值将为 `20`。

      组合路径和查询参数

      您可以在单个路径操作中组合路径和查询参数。

      示例:路径和查询参数

        from fastapi import FastAPI
        app = FastAPI()
        @app.get("/users/{user_id}/items/")async def read_user_items(user_id: int, skip: int = 0, limit: int = 10): return {"user_id": user_id, "skip": skip, "limit": limit}

        在此示例中,`user_id` 是路径参数,而 `skip` 和 `limit` 是查询参数。当您访问 `/users/1/items/?skip=5&limit=20` 时,`user_id` 将为 `1`,`skip` 将为 `5`,`limit` 将为 `20`。

        请求正文

        虽然路径和查询参数非常适合简单数据,但可以使用请求正文发送更复杂的数据。 FastAPI 允许您定义 Pydantic 模型来验证请求主体。

        示例:请求主体

          from fastapi import FastAPIfrom pydantic import BaseModel
          app = FastAPI()
          class Item(BaseModel): name: str description: str = None price: float tax: float = None
          @app.post("/items/")async def create_item(item: Item): return item

          在此示例中,`Item` 模型定义请求主体的结构。当您使用 JSON 主体向 `/items/` 发送 POST 请求时,FastAPI 将根据 `Item` 模型对其进行验证。

          演示

          演示 1:路径参数

            from fastapi import FastAPI
            app = FastAPI()
            @app.get("/books/{book_id}")async def read_book(book_id: int): return {"book_id": book_id}
            # Run the server with: uvicorn demo1:app --reload

            ‍访问 `http://127.0.0.1:8000/books/10`,您将看到 `{"book_id": 10}`。

            演示 2:查询参数

              from fastapi import FastAPI
              app = FastAPI()
              @app.get("/books/")async def read_books(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}
              # Run the server with: uvicorn demo2:app --reload

              访问 `http://127.0.0.1:8000/books/?skip=5&limit=15`,您将看到 `{"skip": 5, "limit": 15}`。

              演示 3:结合路径和查询参数

                from fastapi import FastAPI
                app = FastAPI()
                @app.get("/authors/{author_id}/books/")async def read_author_books(author_id: int, skip: int = 0, limit: int = 10): return {"author_id": author_id, "skip": skip, "limit": limit}
                # Run the server with: uvicorn demo3:app --reload

                访问 `http://127.0.0.1:8000/authors/2/books/?skip=5&limit=15`,您将看到 `{"author_id": 2, "skip": 5, "limit": 15}`。

                让我们探索一些额外的示例,以帮助您更熟悉 FastAPI 中的请求处理和路径操作。这些演示将涵盖一系列场景,包括更复杂的路径参数、组合不同的参数类型以及处理请求主体。

                演示 4:具有多个段的路径参数


                  from fastapi import FastAPI
                  app = FastAPI()
                  @app.get("/files/{file_path:path}")async def read_file(file_path: str): return {"file_path": file_path}
                  # Run the server with: uvicorn demo4:app --reload
                  ‍ ‍ ‍ ‍ ‍ 在此示例中,`file_path` 可以捕获具有多个段的路径,例如 `/files/documents/reports/2024/report.pdf`。当您访问 `http://127.0.0.1:8000/files/documents/reports/2024/report.pdf` 时,您将看到 `{"file_path": "documents/reports/2024/report.pdf"}`。

                  演示 5:可选查询参数

                    from fastapi import FastAPIfrom typing import Optional
                    app = FastAPI()
                    @app.get("/search/")async def search_items(q: Optional[str] = None): if q: return {"query": q} return {"message": "No query provided"}
                    # Run the server with: uvicorn demo5:app --reload

                    在此示例中,`q` 是可选查询参数。如果您访问 `http://127.0.0.1:8000/search/?q=fastapi`,您将看到 `{"query": "fastapi"}`。如果您访问 `http://127.0.0.1:8000/search/` 而不使用查询参数,您将看到 `{"message": "No query provided"}`。

                    演示 6:查询参数的默认值

                      from fastapi import FastAPI
                      app = FastAPI()
                      @app.get("/users/")async def read_users(active: bool = True): return {"active_users_only": active}
                      # Run the server with: uvicorn demo6:app --reload

                      在此示例中,`active` 查询参数的默认值为 `True`。当您访问 `http://127.0.0.1:8000/users/` 时,您将看到 `{"active_users_only": true}`。您可以通过访问 `http://127.0.0.1:8000/users/?active=false` 来覆盖此设置,这将返回 `{"active_users_only": false}`。

                      演示 7:组合路径、查询参数和请求主体

                        from fastapi import FastAPIfrom pydantic import BaseModel
                        app = FastAPI()
                        class Order(BaseModel): item_id: int quantity: int
                        @app.post("/users/{user_id}/orders/")async def create_order(user_id: int, priority: str = "normal", order: Order): return {"user_id": user_id, "priority": priority, "order": order}
                        # Run the server with: uvicorn demo7:app --reload

                        在此示例中,`user_id` 是路径参数,`priority` 是具有默认值的查询参数,`order` 请求主体使用 Pydantic 模型进行验证。要测试这一点,你可以向 `http://127.0.0.1:8000/users/1/orders/?priority=high` 发送一个 POST 请求,其中包含以下 JSON 主体:

                          {    "item_id": 123,    "quantity": 2}

                          ‍这将返回:

                            {    "user_id": 1,    "priority": "high",    "order": {        "item_id": 123,        "quantity": 2    }}

                            演示 8:处理同名的多个查询参数

                              from fastapi import FastAPIfrom typing import List
                              app = FastAPI()
                              @app.get("/tags/")async def read_tags(tags: List[str] = None): return {"tags": tags}
                              # Run the server with: uvicorn demo8:app --reload

                              在此示例中,`tags` 是一个可以接受多个值的查询参数。当您访问 `http://127.0.0.1:8000/tags/?tags=python&tags=fastapi` 时,您将看到 `{"tags": ["python", "fastapi"]}`。

                              演示 9:使用枚举作为路径和查询参数

                                from fastapi import FastAPIfrom enum import Enum
                                app = FastAPI()
                                class Status(str, Enum): pending = "pending" completed = "completed" failed = "failed"
                                @app.get("/tasks/{status}")async def read_task(status: Status): return {"status": status}
                                @app.get("/tasks/")async def read_tasks(status: Status = Status.pending): return {"status": status}
                                # Run the server with: uvicorn demo9:app --reload

                                在此示例中,`Status` 是一个枚举,可用于路径和查询参数。访问 `http://127.0.0.1:8000/tasks/pending` 将返回 `{"status": "pending"}`,访问 `http://127.0.0.1:8000/tasks/?status=completed` 将返回 `{"status": "completed"}`。

                                这些附加演示说明了 FastAPI 在处理不同类型的参数和请求数据方面的多功能性和强大功能。通过使用这些示例,您可以轻松构建更具动态性和功能丰富的 API。

                                FastAPI 使处理带有路径和查询参数的请求变得非常简单。通过使用这些功能,您可以构建灵活、动态且易于理解和维护的 API。FastAPI 生成的交互式 API 文档进一步简化了探索和测试端点的过程。

                                码字不易,喜欢的话点和,分享给更多的朋友。或者关注小编,了解更多新篇章。也可以通过合集查看更多,谢谢!  



                                http://www.mrgr.cn/news/9855.html

                                相关文章:

                              • Gazebo Harmonic 和 ROS2 jazzy 安装和测试
                              • 备战秋招60天算法挑战,Day24
                              • 开放式耳机危害大吗?6点如何挑选合适的开放式耳机!
                              • 嵌入式面经篇十——驱动开发
                              • 【hot100篇-python刷题记录】【搜索二维矩阵】
                              • [JAVA]什么是泛型?泛型在Java中的应用
                              • C#算法之二分查找
                              • python实现简单中文词元化、词典构造、时序数据集封装等
                              • 【Linux】第十六章 高级IO (五种IO模型+fcntl)
                              • 什么是ElasticSearch的深度分页问题?如何解决?
                              • NRK3301语音识别芯片在汽车内饰氛围灯上的应用方案解析
                              • Vue3 获取农历(阴历)日期,并封装日历展示组件
                              • 泰国中小企业局局长率考察团到访深兰科技
                              • SpringBoot天猫商城基于前后端分离+SpringBoot+BootStrap、Vue.js、JQuery+JPA+Redis
                              • Node.js 安装教程
                              • C语言:动态内存管理
                              • 【数学建模】层次分析法
                              • 神经网络算法 - 一文搞懂回归和分类
                              • 献给正在挣扎中的技术人!
                              • C语言:科目二【基础知识】