首页 > 其他分享 >FastAPI快速入门1 Hello World

FastAPI快速入门1 Hello World

时间:2024-06-14 09:55:39浏览次数:9  
标签:__ FastAPI recipe Hello api World router id

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 [19369]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
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
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 for recipe in RECIPES if recipe["id"] == recipe_id]
    if result:
        return result[0]


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格式返回。

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 for recipe in RECIPES if recipe["id"] == recipe_id]
    if result:
        return result[0]


# New addition, query parameter
# https://fastapi.tiangolo.com/tutorial/query-params/
@api_router.get("/search/", status_code=200)
def search_recipes(
    keyword: Optional[str] = None, max_results: Optional[int] = 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格式。

标签:__,FastAPI,recipe,Hello,api,World,router,id
From: https://www.cnblogs.com/testing-/p/18246681

相关文章

  • HIT CSAPP 计算机系统大作业 程序人生-Hello’s P2P From Program to Process
    摘 要本文借助hello.c跌宕起伏的一生——P2P(FromProgramToProcess)、020(FromZero-0toZero-0)从源代码到可执行程序以及和计算机系统硬件的配合,从计算机系统的角度阐述从源代码到可执行程序的转变,以及在计算机系统当中作为众多进程中的一员的运行过程。源程序首先经......
  • FastAPI-9 服务层
    9服务层本章阐述了服务层,即中间层。9.1定义服务服务层是网站的核心,它接收来自多个来源的请求,访问作为网站DNA的数据,并返回响应。常见的服务模式包括以下组合:创建/检索/更改(部分或全部)/删除一件事/多件事在RESTful路由器层,名词是资源。在本书中,我们的资源最初将包括隐......
  • FastAPI-7:框架比较(Flask、Django及FastAPI)
    7框架比较(Flask、Django及FastAPI)关于一个新的Web框架,您可能想知道的第一件事就是如何入门,而一种自上而下的方法就是定义路由(从URL和HTTP方法到函数的映射)。7.1FlaskFlask自称是微框架。它提供基本功能,你可以根据需要下载第三方软件包进行补充。它比Django小,入门时学习......
  • 用fastapi和sse创建流式输出接口
    示例为调用huggingface的大模型,使其流式输出fromfastapiimportFastAPI,RequestimportrequestsimportjsonimportosfrompydanticimportBaseModelfromtransformersimportAutoTokenizer,AutoModelForCausalLM,TextStreamer,TextIteratorStreamerfromsse_star......
  • FastAPI-8:Web层
    8Web层本章将进一步介绍FastAPI应用程序的顶层(也可称为接口层或路由器层)及其与服务层和数据层的集成。一般来说,我们如何处理信息?与大多数网站一样,我们的网站将提供以下方法:检索创建修改替换删除8.1插曲:自顶向下、自底向上、中间向外?(Top-Down,Bottom-Up,Middle-Out......
  • python系列:python fastapi + uvicorn 记录日志的最佳实践,结合nb_log
    pythonfastapi+uvicorn记录日志的最佳实践,结合nb_logpythonfastapi+uvicorn记录日志的最佳实践,结合nb_logpythonfastapi+uvicorn记录日志的最佳实践,结合nb_logpythonfastapi+uvicorn记录日志的最佳实践,要记录对fastapi什么时候请求了什么url和入......
  • FASM之Hello消息框
    include'win32ax.inc'.codestart: invokeMessageBox,HWND_DESKTOP,"你好!","hello",MB_OK invokeExitProcess,0.endstart主要使用invoke指令调用MessageBox消息框函数。MessageBox后面的四个参数:第一个参数,HWND_DESKTOP,表示桌面窗口句柄。第二个参数,"你好!",是......
  • FastAPI+MemFire Cloud+LangChain开发ChatGPT应用
    为什么选择这三个组合OpenAI官方SDK是Python,此开发语言首选PythonFastAPI是Python语言编写的高性能的现代化Web框架MemFireCloud提供向量数据库支持,向量数据库是开发知识库应用的必选项MemFireCloud提供Supabase托管,LangChain原生支持SupabaseAPILangChain是AI应用开发......
  • SDL3 入门(1):Hello, SDL3!
    在本系列中我们使用WindowsTerminal+Powershell组合作为我们在Windows系统下的终端工具,Windows11自带该环境。你也可以使用任意自己喜欢的终端环境代替,或使用鼠标执行等价的操作。源码准备我们使用git管理我们的项目,所以首先我们创建一个名为"hello_sdl3"的目录并......
  • python系列:FastAPI系列 10-路由管理APIRouter
    FastAPI系列10-路由管理APIRouterFastAPI系列10-路由管理APIRouter前言一、路由管理APIRouter二、FastAPI主体总结FastAPI系列10-路由管理APIRouter前言在fastapi中也有类似的功能通过APIRouter来管理一、路由管理APIRouter正在开发一个应用程序或We......