-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import types | |
from fastapi import FastAPI | |
from pinwheel.openapi import custom_openapi | |
app = FastAPI() | |
app.openapi = types.MethodType(custom_openapi, app) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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