美文网首页fastapi学习文档fastapi
fastapi教程翻译(二十一):Path Operation

fastapi教程翻译(二十一):Path Operation

作者: warmsirius | 来源:发表于2019-12-12 11:04 被阅读0次

    一、 OpenAPI中operationId

    警告:

    如果您不是OpenAPI中的“专家”,则可能不需要它。

    您可以使用参数operation_id设置要在路径操作中使用的OpenAPI operationId。

    您必须确保每个操作的唯一性。

    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/", operation_id="some_specific_id_you_define")
    async def read_items():
        return [{"item_id": "Foo"}]
    

    使用路径操作函数名称作为operationId,如果要使用API的函数名作为operationId,则可以遍历所有API并使用其APIRoute.name覆盖每个路径操作的operation_id。

    您应该在添加所有路径操作之后执行此操作。

    from fastapi import FastAPI
    from fastapi.routing import APIRoute
    
    app = FastAPI()
    
    
    @app.get("/items/")
    async def read_items():
        return [{"item_id": "Foo"}]
    
    
    def use_route_names_as_operation_ids(app: FastAPI) -> None:
        """
        Simplify operation IDs so that generated API clients have simpler function
        names.
    
        Should be called only after all routes have been added.
        """
        for route in app.routes:
            if isinstance(route, APIRoute):
                route.operation_id = route.name  # in this case, 'read_items'
    
    
    use_route_names_as_operation_ids(app)
    

    建议:
    如果您手动调用app.openapi(),则应在此之前更新operationIds。

    警告:
    如果这样做,则必须确保每个路径操作函数都具有唯一的名称。(即使操作函数在不同的模块中.)

    二、从OpenAPI中排除

    要从生成的OpenAPI架构(以及自动文档系统)中排除路径操作,请使用参数include_in_schema并将其设置为 False:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/items/", include_in_schema=False)
    async def read_items():
        return [{"item_id": "Foo"}]
    

    三、文档字符串的高级描述

    您可以限制OpenAPI的路径操作函数的文档字符串中使用的行。

    添加\f(转义的“换页符”字符)会导致FastAPI此时截断用于OpenAPI的输出。

    它不会显示在文档中,但是其他工具(例如Sphinx)将可以使用其余的工具。

    from typing import Set
    
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    app = FastAPI()
    
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: Set[str] = []
    
    
    @app.post("/items/", response_model=Item, summary="Create an item")
    async def create_item(*, item: Item):
        """
        Create an item with all the information:
    
        - **name**: each item must have a name
        - **description**: a long description
        - **price**: required
        - **tax**: if the item doesn't have tax, you can omit this
        - **tags**: a set of unique tag strings for this item
        \f
        :param item: User input.
        """
        return item
    

    相关文章

      网友评论

        本文标题:fastapi教程翻译(二十一):Path Operation

        本文链接:https://www.haomeiwen.com/subject/giizgctx.html