Skip to content

Instantly share code, notes, and snippets.

@pelzhaus
Created March 25, 2021 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pelzhaus/04ffeab8fc4161e34c03c8ddc4545d68 to your computer and use it in GitHub Desktop.
Save pelzhaus/04ffeab8fc4161e34c03c8ddc4545d68 to your computer and use it in GitHub Desktop.
Once we added our own OpenAPI hook, it became easy to extend FastAPI's generation. The PinwheelPublicBaseModel.generate_examples() function is a custom method that finds the referenced Pydantic model in our codebase and produces a JSON example of that model.
import types
from fastapi import FastAPI
from pinwheel.openapi import custom_openapi
app = FastAPI()
app.openapi = types.MethodType(custom_openapi, app)
from typing import Dict
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from pinwheel.models import PinwheelPublicBaseModel
def add_examples_to_schema(openapi_schema: Dict) -> None:
for path, verbs in openapi_schema["paths"].items():
for verb, request in verbs.items():
success_response = request["responses"]["200"]["content"]["application/json"]
response_model_ref = success_response["schema"]["$ref"]
success_response["examples"] = PinwheelPublicBaseModel.generate_examples(
response_model_ref
)
def custom_openapi(app: FastAPI, *args, **kwargs) -> Dict:
"""
A custom wrapper around FastAPI's OpenAPI generator.
"""
openapi_schema = get_openapi(
title="Pinwheel",
description="Pinwheel is the API for Payroll",
version="1.0.0",
routes=app.routes
)
add_examples_to_schema(openapi_schema)
app.openapi_schema = openapi_schema
return app.openapi_schema
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment