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

推荐订阅源

J
Java Code Geeks
月光博客
月光博客
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss
Stack Overflow Blog
Stack Overflow Blog
Blog — PlanetScale
Blog — PlanetScale
aimingoo的专栏
aimingoo的专栏
U
Unit 42
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
T
Tailwind CSS Blog
N
Netflix TechBlog - Medium
B
Blog
博客园_首页
G
Google Developers Blog
Recent Announcements
Recent Announcements
博客园 - 【当耐特】
P
Proofpoint News Feed
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
Last Week in AI
Last Week in AI

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: