【问题标题】:Test the proper functioning of a FastAPI instance测试 FastAPI 实例的正常运行
【发布时间】:2022-01-20 12:49:17
【问题描述】:

我想通过 POST 操作测试 FastAPI 实例的正确功能。第一步是像普通的Python函数一样测试操作,如下:

import uvicorn
from fastapi import Request, FastAPI
from typing import List, Optional
from pydantic import BaseModel

app = FastAPI()

class Company(BaseModel):
    id: int
    name: str
    vat: str
    website: Optional[str] = None

@app.post("/processes/new/")
def new_process(id_user: int, companies: List[Company], stop_words: str, blacklist: List[str]):
    # some code
    return companies[0].dict() # just an example of output

if __name__ == "__main__":
    id_user = 1
    companies = [Company(id=1, name="ABC srl", vat="0123456789", website="https://www.abc.it/"), Company(id=2, name="XYZ srl", vat="9876543210", website="https://www.xyz.it/")]
    stop_words = "a;the;and"
    blacklist = ["https://www.def.it/", "https://www.ghi.it/"]
    print(new_process(id_user, companies, stop_words, blacklist))

一切正常。现在我进行以下更改以便能够测试 API:

@app.post("/processes/new/")
async def new_process(id_user: int, companies: List[Company], stop_words: str, blacklist: List[str]):
    # some code
    return companies[0].dict() # just an example of output

if __name__ == "__main__":
    uvicorn(app, host="127.0.0.1", port=8000)

我有两个问题:

  1. 如果我想在浏览器上测试操作,我该怎么办?我应该使用 Postman 之类的东西吗?如果是这样,我应该以什么格式输入测试数据?

  2. 另一方面,如果我想通过POST 请求测试功能?我应该使用requests 模块吗?在这种情况下,我应该以哪种格式输入输入数据?

【问题讨论】:

标签: python python-requests postman fastapi


【解决方案1】:

您可以同时使用 Postman 或带有请求的脚本,但有一种更快的方法来手动测试您的 API。 FastAPI 具有内置的 Swagger(OpenAPI) 支持,因此只需转到 127.0.0.1:8000/docs 并测试您的 API 端点。

您可以查看更多详细信息:https://fastapi.tiangolo.com/tutorial/first-steps/?h=openapi#interactive-api-docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    相关资源
    最近更新 更多