【碎片】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

                                相关文章

                                Python使用FastAPI实现大文件分片上传与断点续传功能

                                《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

                                python获取指定名字的程序的文件路径的两种方法

                                《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

                                SpringBoot 获取请求参数的常用注解及用法

                                《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

                                HTTP 与 SpringBoot 参数提交与接收协议方式

                                《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

                                SpringBoot路径映射配置的实现步骤

                                《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

                                python中的显式声明类型参数使用方式

                                《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

                                Go语言使用Gin处理路由参数和查询参数

                                《Go语言使用Gin处理路由参数和查询参数》在WebAPI开发中,处理路由参数(PathParameter)和查询参数(QueryParameter)是非常常见的需求,下面我们就来看看Go语言... 目录一、路由参数 vs 查询参数二、Gin 获取路由参数和查询参数三、示例代码四、运行与测试1. 测试编程路

                                Python lambda函数(匿名函数)、参数类型与递归全解析

                                《Pythonlambda函数(匿名函数)、参数类型与递归全解析》本文详解Python中lambda匿名函数、灵活参数类型和递归函数三大进阶特性,分别介绍其定义、应用场景及注意事项,助力编写简洁高效... 目录一、lambda 匿名函数:简洁的单行函数1. lambda 的定义与基本用法2. lambda

                                python设置环境变量路径实现过程

                                《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

                                Python Web框架Flask、Streamlit、FastAPI示例详解

                                《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre