翼度科技»论坛 编程开发 python 查看内容

FastAPI快速入门1 Hello World

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
1 Hello World

1.1 Hello World


  • ch01/main.py
  1. from fastapi import FastAPI, APIRouter
  2. # 1
  3. app = FastAPI(
  4.     title="Recipe API", openapi_url="/openapi.json"
  5. )
  6. # 2
  7. api_router = APIRouter()
  8. # 3
  9. @api_router.get("/", status_code=200)
  10. def root() -> dict:
  11.     """
  12.     Root Get
  13.     """
  14.     return {"msg": "Hello, World!"}
  15. # 4
  16. app.include_router(api_router)
  17. # 5
  18. if __name__ == "__main__":
  19.     # Use this for debugging purposes only
  20.     import uvicorn
  21.     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依赖于这个网络服务器(稍后我们将详细讨论)。

  • 执行:
  1. $ python main.py
  2. INFO:     Started server process [19369]
  3. INFO:     Waiting for application startup.
  4. INFO:     Application startup complete.
  5. INFO:     Uvicorn running on http://0.0.0.0:8001 (Press CTRL+C to quit)
复制代码

如果能看到 "Hello, World!"(你好,世界!)的响应,则说明 API 已正常工作。以上是Chrome的效果,Firefox的如下:

接下来访问localhost:8001/docs,您应该会看到如下界面:

这是FastAPI默认提供的交互式文档,因为该框架是围绕OpenAPI标准构建的。这些文档页面是交互式的,随着我们添加更多的端点并描述代码中预期的输入/输出值,文档页面的细节会越来越多。
参考资料

1.2 自动文档

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

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

  • SwaggerUI


  • ReDoc

这两个选项都提供交互式文档页面,您可以在其中输入请求数据并触发响应,这对于手动测试非常方便。
1.3路径参数


  • ch01/main2.py
  1. from fastapi import FastAPI, APIRouter
  2. RECIPES = [
  3.     {
  4.         "id": 1,
  5.         "label": "Chicken Vesuvio",
  6.         "source": "Serious Eats",
  7.         "url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
  8.     },
  9.     {
  10.         "id": 2,
  11.         "label": "Chicken Paprikash",
  12.         "source": "No Recipes",
  13.         "url": "http://norecipes.com/recipe/chicken-paprikash/",
  14.     },
  15.     {
  16.         "id": 3,
  17.         "label": "Cauliflower and Tofu Curry Recipe",
  18.         "source": "Serious Eats",
  19.         "url": "http://www.seriouseats.com/recipes/2011/02/cauliflower-and-tofu-curry-recipe.html",
  20.     },
  21. ]
  22. app = FastAPI(title="Recipe API", openapi_url="/openapi.json")
  23. api_router = APIRouter()
  24. @api_router.get("/", status_code=200)
  25. def root() -> dict:
  26.     """
  27.     Root GET
  28.     """
  29.     return {"msg": "Hello, World!"}
  30. # New addition, path parameter
  31. # https://fastapi.tiangolo.com/tutorial/path-params/
  32. @api_router.get("/recipe/{recipe_id}", status_code=200)
  33. def fetch_recipe(*, recipe_id: int) -> dict:
  34.     """
  35.     Fetch a single recipe by ID
  36.     """
  37.     result = [recipe for recipe in RECIPES if recipe["id"] == recipe_id]
  38.     if result:
  39.         return result[0]
  40. app.include_router(api_router)
  41. if __name__ == "__main__":
  42.     # Use this for debugging purposes only
  43.     import uvicorn
  44.     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格式返回。

1.4 查询参数


  • ch01/main3.py
  1. from fastapi import FastAPI, APIRouter
  2. from typing import Optional
  3. RECIPES = [
  4.     {
  5.         "id": 1,
  6.         "label": "Chicken Vesuvio",
  7.         "source": "Serious Eats",
  8.         "url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
  9.     },
  10.     {
  11.         "id": 2,
  12.         "label": "Chicken Paprikash",
  13.         "source": "No Recipes",
  14.         "url": "http://norecipes.com/recipe/chicken-paprikash/",
  15.     },
  16.     {
  17.         "id": 3,
  18.         "label": "Cauliflower and Tofu Curry Recipe",
  19.         "source": "Serious Eats",
  20.         "url": "http://www.seriouseats.com/recipes/2011/02/cauliflower-and-tofu-curry-recipe.html",
  21.     },
  22. ]
  23. app = FastAPI(title="Recipe API", openapi_url="/openapi.json")
  24. api_router = APIRouter()
  25. @api_router.get("/", status_code=200)
  26. def root() -> dict:
  27.     """
  28.     Root GET
  29.     """
  30.     return {"msg": "Hello, World!"}
  31. @api_router.get("/recipe/{recipe_id}", status_code=200)
  32. def fetch_recipe(*, recipe_id: int) -> dict:
  33.     """
  34.     Fetch a single recipe by ID
  35.     """
  36.     result = [recipe for recipe in RECIPES if recipe["id"] == recipe_id]
  37.     if result:
  38.         return result[0]
  39. # New addition, query parameter
  40. # https://fastapi.tiangolo.com/tutorial/query-params/
  41. @api_router.get("/search/", status_code=200)
  42. def search_recipes(
  43.     keyword: Optional[str] = None, max_results: Optional[int] = 10
  44. ) -> dict:
  45.     """
  46.     Search for recipes based on label keyword
  47.     """
  48.     if not keyword:
  49.         # we use Python list slicing to limit results
  50.         # based on the max_results query parameter
  51.         return {"results": RECIPES[:max_results]}
  52.     results = filter(lambda recipe: keyword.lower() in recipe["label"].lower(), RECIPES)
  53.     return {"results": list(results)[:max_results]}
  54. app.include_router(api_router)
  55. if __name__ == "__main__":
  56.     # Use this for debugging purposes only
  57.     import uvicorn
  58.     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格式。

来源:https://www.cnblogs.com/testing-/p/18246681
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具