6

FastAPI testing and OpenAPI doc generation

 8 months ago
source link: https://jdhao.github.io/2023/09/20/fastapi-testing-and-openapi-spec/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

FastAPI testing and OpenAPI doc generation

2023-09-20237 words 2 mins read 70 times read

Some notes on developing a web application with FastAPI.

Testing

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:

pytest .

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": "[email protected]",
            "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)

Author jdhao

LastMod 2023-09-21

License CC BY-NC-ND 4.0

Prev Next


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK