惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
V
Visual Studio Blog
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
B
Blog
I
InfoQ
博客园 - 三生石上(FineUI控件)
阮一峰的网络日志
阮一峰的网络日志
F
Fortinet All Blogs
H
Help Net Security
博客园 - Franky
宝玉的分享
宝玉的分享
博客园 - 司徒正美
C
Check Point Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Jina AI
Jina AI
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
A
About on SuperTechFans
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
FastAPI testing and OpenAPI doc generation
2023-09-21 · via jdhao's digital space

Some notes on developing a web application with FastAPI.

FastAPI provides a fastapi.testclient module to help us test the application.

# content of application.py
from fastapi import FastAPI


app = FastAPI()

@app.get("/")
def index():
    return {'msg': 'hello world!'}

You can test the endpoints with TestClient class from testclient module.

# content of test_application.py
from application import app
from fastapi.testclient import TestClient
from fastapi import status


client = TestClient(app)

def test_root():
    response = app.get('/')

    assert response.status_code == status.HTTP_200_OK
    assert response.json() == {'msg': 'hello world!'}

Then you can test your application with pytest:

ref:

Generate OpenAPI specification#

The app we create using FastAPI has a openapi() method. Under the hood, it is calling the get_openapi() method from the module fastapi.openapi.utils.

We can override this method to customize the OpenAPI schema.

# content of application.py
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi


app = FastAPI()

@app.get("/")
def index():
    return {'msg': "hello world"}


def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema

    openapi_schema = get_openapi(
        title="My Awesome Application",
        version=app.version,
        contact={
            "name": "Your Name",
            "email": "your_name@host.com",
            "url": "https://www.example.com"
        },
        openapi_version=app.openapi_version,
        summary="This implements my awesome application with fastAPI",
        description="""
        some long description about your application.
        """,
        routes=app.routes,
    )
    app.openapi_schema = openapi_schema

    return app.openapi_schema


app.openapi = custom_openapi

Then if you want to generate the OpenAPI spec, it is easy:

# content of generate_openapi_spec.py
import json

from application import app

with open('path/to/openapi.json', 'w') as f:
    json.dump(app.openapi(), indent=4)

ref: