数据人与超自然意识 发表于 2024-6-14 09:14:52

FastAPI快速入门1 Hello World

1 Hello World

1.1 Hello World


[*]ch01/main.py
from fastapi import FastAPI, APIRouter

# 1
app = FastAPI(
    title="Recipe API", openapi_url="/openapi.json"
)

# 2
api_router = APIRouter()

# 3
@api_router.get("/", status_code=200)
def root() -> dict:
    """
    Root Get
    """
    return {"msg": "Hello, World!"}

# 4
app.include_router(api_router)


# 5
if __name__ == "__main__":
    # Use this for debugging purposes only
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")

[*]1
实例化FastAPI应用步伐对象,它是一个Python类,为您的API提供所有功能。openapi_url="/openapi.json"部门可不提供,默认值就是如此。

[*]2
实例化APIRouter,这样我们就能对API端点进行分组(并指定版本和其他配置,稍后我们将具体先容)

[*]3
在根函数中添加 @api_router.get("/", status_code=200) 装饰器为应用步伐接口定义了根本的GET端点。

[*]4
我们使用app对象的include_router方法在FastAPI对象上注册第2步中创建的路由器。

[*]5
适用于直接调用模块的环境,即运行python app/main.py。在这种环境下,我们必要导入uvicorn,由于FastAPI依赖于这个网络服务器(稍后我们将具体讨论)。

[*]实行:
$ python main.py
INFO:   Started server process
INFO:   Waiting for application startup.
INFO:   Application startup complete.
INFO:   Uvicorn running on http://0.0.0.0:8001 (Press CTRL+C to quit)https://img2024.cnblogs.com/blog/3174021/202406/3174021-20240614082633647-1734234258.png
假如能看到 "Hello, World!"(你好,天下!)的相应,则说明 API 已正常工作。以上是Chrome的效果,Firefox的如下:
https://img2024.cnblogs.com/blog/3174021/202406/3174021-20240614082834644-528891566.png
接下来访问localhost:8001/docs,您应该会看到如下界面:
https://img2024.cnblogs.com/blog/3174021/202406/3174021-20240613201829748-127975492.png
这是FastAPI默认提供的交互式文档,由于该框架是围绕OpenAPI标准构建的。这些文档页面是交互式的,随着我们添加更多的端点并描述代码中预期的输入/输出值,文档页面的细节会越来越多。
参考资料


[*]软件测试精品书籍文档下载持续更新 https://github.com/china-testing/python-testing-examples 请点赞,谢谢!
[*]本文涉及的python测试开辟库 谢谢点赞! https://github.com/china-testing/python_cn_resouce
[*]python精品书籍下载 https://github.com/china-testing/python_cn_resouce/blob/main/python_good_books.md
[*]Linux精品书籍下载 https://www.cnblogs.com/testing-/p/17438558.html
1.2 自动文档

FastAPI是围绕OpenAPI规范(从前称为swagger)标准经心打造的。在FastAPI中,通过对端点进行编码,您可以自动编写API文档。FastAPI 将您的端点细节映射到JSON模式文档中。生成的文档(假如足够具体)可以显示以下内容:

[*]路径操作
[*]参数
[*]请求正文
[*]安全具体信息,如所需的header
开箱即用,可选择您喜欢的文档 UI 显示方式:

[*]SwaggerUI
https://img2024.cnblogs.com/blog/3174021/202406/3174021-20240613202120929-1661941199.png

[*]ReDoc
https://img2024.cnblogs.com/blog/3174021/202406/3174021-20240613202158636-800300151.png
这两个选项都提供交互式文档页面,您可以在此中输入请求数据并触发相应,这对于手动测试非常方便。
1.3路径参数


[*]ch01/main2.py
from fastapi import FastAPI, APIRouter


RECIPES = [
    {
      "id": 1,
      "label": "Chicken Vesuvio",
      "source": "Serious Eats",
      "url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
    },
    {
      "id": 2,
      "label": "Chicken Paprikash",
      "source": "No Recipes",
      "url": "http://norecipes.com/recipe/chicken-paprikash/",
    },
    {
      "id": 3,
      "label": "Cauliflower and Tofu Curry Recipe",
      "source": "Serious Eats",
      "url": "http://www.seriouseats.com/recipes/2011/02/cauliflower-and-tofu-curry-recipe.html",
    },
]


app = FastAPI(title="Recipe API", openapi_url="/openapi.json")

api_router = APIRouter()


@api_router.get("/", status_code=200)
def root() -> dict:
    """
    Root GET
    """
    return {"msg": "Hello, World!"}


# New addition, path parameter
# https://fastapi.tiangolo.com/tutorial/path-params/
@api_router.get("/recipe/{recipe_id}", status_code=200)
def fetch_recipe(*, recipe_id: int) -> dict:
    """
    Fetch a single recipe by ID
    """

    result = == recipe_id]
    if result:
      return result


app.include_router(api_router)


if __name__ == "__main__":
    # Use this for debugging purposes only
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")我们在RECIPE字典列表中创建了一些示例配方数据。就现在而言,这只是最根本、最根本的内容,但可以满足我们的学习目的。在本系列教程的反面,我们将扩展这个数据集,并将其存储到数据库中。
我们创建了新的GET端点 /recipe/{recipe_id}。这里的大括号表示参数值,必要与端点函数 fetch_recipe 的参数之一相匹配。
fetch_recipe函数定义了新端点的逻辑。与URL路径参数相匹配的函数参数的范例提示被FastAPI用来实行自动验证和转换。我们稍后将看到现实操作。
我们通过一个带有ID条件检查的简单列表理解来模拟按ID从数据库中获取数据。然后,FastAPI将数据序列化并以JSON格式返回。
https://img2024.cnblogs.com/blog/3174021/202406/3174021-20240614083531876-688962937.png
1.4 查询参数


[*]ch01/main3.py
from fastapi import FastAPI, APIRouter

from typing import Optional


RECIPES = [
    {
      "id": 1,
      "label": "Chicken Vesuvio",
      "source": "Serious Eats",
      "url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
    },
    {
      "id": 2,
      "label": "Chicken Paprikash",
      "source": "No Recipes",
      "url": "http://norecipes.com/recipe/chicken-paprikash/",
    },
    {
      "id": 3,
      "label": "Cauliflower and Tofu Curry Recipe",
      "source": "Serious Eats",
      "url": "http://www.seriouseats.com/recipes/2011/02/cauliflower-and-tofu-curry-recipe.html",
    },
]


app = FastAPI(title="Recipe API", openapi_url="/openapi.json")

api_router = APIRouter()


@api_router.get("/", status_code=200)
def root() -> dict:
    """
    Root GET
    """
    return {"msg": "Hello, World!"}


@api_router.get("/recipe/{recipe_id}", status_code=200)
def fetch_recipe(*, recipe_id: int) -> dict:
    """
    Fetch a single recipe by ID
    """

    result = == recipe_id]
    if result:
      return result


# New addition, query parameter
# https://fastapi.tiangolo.com/tutorial/query-params/
@api_router.get("/search/", status_code=200)
def search_recipes(
    keyword: Optional = None, max_results: Optional = 10
) -> dict:
    """
    Search for recipes based on label keyword
    """
    if not keyword:
      # we use Python list slicing to limit results
      # based on the max_results query parameter
      return {"results": RECIPES[:max_results]}

    results = filter(lambda recipe: keyword.lower() in recipe["label"].lower(), RECIPES)
    return {"results": list(results)[:max_results]}


app.include_router(api_router)


if __name__ == "__main__":
    # Use this for debugging purposes only
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")我们创建了一个新的GET端点/search/。注意它没有路径参数,这一点我们在第二部门中已经讨论过了search_recipes 函数定义了新端点的逻辑。它的参数代表端点的查询参数。有两个参数:关键字和 max_results。这意味着包含这两个查询参数的(本地)查询大概如下所示: http://localhost:8001/search/?keyword=chicken&max_results=2
请注意,我们为每个参数指定了范例和默认值。这两个参数都是来自 Python 标准库范例模块的可选参数。FastAPI 可以使用这些原生Python范例声明来理解参数不必要设置(假如我们希望参数是强制性的,我们就可以省略可选参数)
这两个参数也有默认值,通过 = 符号指定,例如 max_result 查询参数的默认值是 10。假如请求中没有指定这些参数,则将使用默认值。
我们使用Python列表切分来限制效果,从而实现一些根本的搜索功能。我们使用Python filter对玩具数据集进行非常根本的关键字搜索。搜索完成后,框架会将数据序列化为JSON格式。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: FastAPI快速入门1 Hello World