Skip to main content

FastAPI testing and OpenAPI doc generation

·239 words·2 mins

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 .

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: