1

FastAPI generates the "openapi.json" file and provides an interface to it.

For an experiment I need to replace this with a third party file.

from pathlib import Path
import json
app.openapi_schema = json.loads(Path(r"myopenapi.json").read_text())

when I put this code behind a endpoint, for example "/"

@app.get("/", include_in_schema=FULL_SCHEMA)
def read_root():
    # code here

After calling the endpoint once, the loaded myopenapi.json is displayed for the "/docs" interface and the original is overwritten. The functionality has not changed, the old definitions still work.

I would like to be able to make the switch directly after FastAPI has completed the setup and all end points are created.

Putting this in the Startup code block doesn't work (async def lifespan(app: FastAPI):) - when this reaches yield the app.openapi _schema is not created yet.

Where is the right place to change the FastAPI app after generation?

FastAPI is started with the command:

uvicorn.run(app, host=SERVER_HOST, port=SERVER_PORT, workers=1)
2
  • 2
    Does this help? Commented May 27, 2024 at 17:18
  • 1
    You might find this, as well as this and this helpful as well. Commented May 29, 2024 at 5:36

1 Answer 1

2

@Helen had the right idea in the comment section

And the "problem" was that the openapi schema in FastAPI is created on demand and not on startup.

Adding this code works.

Note: I chose to use the original swagger.yaml I was given over converting it to json for this test.

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema

    openapi_schema= yaml.safe_load(Path("swagger.yaml").read_text())

    # remove the server from the schema
    del openapi_schema['servers']

    app.openapi_schema = openapi_schema
    return app.openapi_schema

app = FastAPI()
app.openapi = custom_openapi

And it's also do-able to add an exeption handler on StarletteHTTPException and then switch out 404 errors with 501 for those not implemented faked endpoints.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.