Skip to main content
  1. Posts/

FastAPI testing and OpenAPI doc generation

··239 words·2 mins·
Table of Contents

Some notes on developing a web application with FastAPI.


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

# content of
from fastapi import FastAPI

app = FastAPI()

def index():
    return {'msg': 'hello world!'}

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

# content of
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
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

app = FastAPI()

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",
            "name": "Your Name",
            "email": "",
            "url": ""
        summary="This implements my awesome application with fastAPI",
        some long description about your application.
    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
import json

from application import app

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



How to Deploy Fastapi Application with Docker
·508 words·3 mins
How to Parse Query Param With Multiple Values in FastAPI
·316 words·2 mins
Configure Python logging with dictConfig
··503 words·3 mins