【碎片】FastAPI 路径参数

2024-08-26 14:20
文章标签 参数 路径 fastapi 碎片

本文主要是介绍【碎片】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 文档进一步简化了探索和测试端点的过程。

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


                                这篇关于【碎片】FastAPI 路径参数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



                                http://www.chinasem.cn/article/1108813

                                相关文章

                                一文带你了解SpringBoot中启动参数的各种用法

                                《一文带你了解SpringBoot中启动参数的各种用法》在使用SpringBoot开发应用时,我们通常需要根据不同的环境或特定需求调整启动参数,那么,SpringBoot提供了哪些方式来配置这些启动参... 目录一、启动参数的常见传递方式二、通过命令行参数传递启动参数三、使用 application.pro

                                Linux修改pip和conda缓存路径的几种方法

                                《Linux修改pip和conda缓存路径的几种方法》在Python生态中,pip和conda是两种常见的软件包管理工具,它们在安装、更新和卸载软件包时都会使用缓存来提高效率,适当地修改它们的缓存路径... 目录一、pip 和 conda 的缓存机制1. pip 的缓存机制默认缓存路径2. conda 的缓

                                基于@RequestParam注解之Spring MVC参数绑定的利器

                                《基于@RequestParam注解之SpringMVC参数绑定的利器》:本文主要介绍基于@RequestParam注解之SpringMVC参数绑定的利器,具有很好的参考价值,希望对大家有所帮助... 目录@RequestParam注解:Spring MVC参数绑定的利器什么是@RequestParam?@

                                Windows系统下如何查找JDK的安装路径

                                《Windows系统下如何查找JDK的安装路径》:本文主要介绍Windows系统下如何查找JDK的安装路径,文中介绍了三种方法,分别是通过命令行检查、使用verbose选项查找jre目录、以及查看... 目录一、确认是否安装了JDK二、查找路径三、另外一种方式如果很久之前安装了JDK,或者在别人的电脑上,想

                                SpringBoot接收JSON类型的参数方式

                                《SpringBoot接收JSON类型的参数方式》:本文主要介绍SpringBoot接收JSON类型的参数方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、jsON二、代码准备三、Apifox操作总结一、JSON在学习前端技术时,我们有讲到过JSON,而在

                                Python FastAPI入门安装使用

                                《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

                                Python中Windows和macOS文件路径格式不一致的解决方法

                                《Python中Windows和macOS文件路径格式不一致的解决方法》在Python中,Windows和macOS的文件路径字符串格式不一致主要体现在路径分隔符上,这种差异可能导致跨平台代码在处理文... 目录方法 1:使用 os.path 模块方法 2:使用 pathlib 模块(推荐)方法 3:统一使

                                一文教你解决Python不支持中文路径的问题

                                《一文教你解决Python不支持中文路径的问题》Python是一种广泛使用的高级编程语言,然而在处理包含中文字符的文件路径时,Python有时会表现出一些不友好的行为,下面小编就来为大家介绍一下具体的... 目录问题背景解决方案1. 设置正确的文件编码2. 使用pathlib模块3. 转换路径为Unicod

                                JAVA虚拟机中 -D, -X, -XX ,-server参数使用

                                《JAVA虚拟机中-D,-X,-XX,-server参数使用》本文主要介绍了JAVA虚拟机中-D,-X,-XX,-server参数使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录一、-D参数二、-X参数三、-XX参数总结:在Java开发过程中,对Java虚拟机(JVM)的启动参数进

                                解读docker运行时-itd参数是什么意思

                                《解读docker运行时-itd参数是什么意思》在Docker中,-itd参数组合用于在后台运行一个交互式容器,同时保持标准输入和分配伪终端,这种方式适合需要在后台运行容器并保持交互能力的场景... 目录docker运行时-itd参数是什么意思1. -i(或 --interactive)2. -t(或 --