-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Description
For the FastAPI plugin, currently the code generated looks something like this in default_api.py stub code:
async def method_post(
) ->None:
if not BaseDefaultApi.subclasses:
raise HTTPException(status_code=500, detail="Not implemented")
return await BaseDefaultApi.subclasses[0]().method_post()
So the usual way to implement my code would be to create a class that inherits from BaseDefaultApi class, implement the respective function for that API, and the part of the code above will automatically route to the my class. If there are no subclasses inheriting the BaseDefaultApi class then my default 501-Not Implemented will be returned. So far so good.
However, lets say I have 2 function definitions in my OpenAPI specs, and I only implemented one of the functions. If a client tries to call the function that I did not implement, instead of getting back 501-Not Implemented, the client will receive 500-Internal Server Error, and on the server side the logs will be spammed with exceptions because the code above does not check if the function implementation exist before calling and will attempt to call the function in the subclass I created, but the function is not in my subclass it throws error.
A better version will be something like this:
async def method_post(
) ->None:
if not BaseDefaultApi.subclasses or "method_post" not in BaseDefaultApi.subclasses[0].__dict__:
raise HTTPException(status_code=501, detail="Not implemented")
return await BaseDefaultApi.subclasses[0]().method_post()
This way if some functions are not implemented yet, the server side logs will not spam errors, the code above will route to the "return await" portion and client will receive 501-Not Implemented instead of 500-Internal Server Error
I have updated the mustache file for FastAPI as attached. And the diff I made is as follows:
$ git diff modules/openapi-generator/src/main/resources/python-fastapi/api.mustache
diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache
index 7c87ef7543c..b85d4b2d2ea 100644
--- a/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache
+++ b/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache
@@ -66,7 +66,7 @@ async def {{operationId}}(
{{/hasAuthMethods}}
) -> {{returnType}}{{^returnType}}None{{/returnType}}:
{{#notes}}"""{{.}}"""
- {{/notes}}if not Base{{classname}}.subclasses:
+ {{/notes}}if not Base{{classname}}.subclasses or "{{operationId}}" not in Base{{classname}}.subclasses[0].__dict__:
raise HTTPException(status_code=500, detail="Not implemented")
return await Base{{classname}}.subclasses[0]().{{operationId}}({{#allParams}}{{>impl_argument}}{{^-last}}, {{/-last}}{{/allParams}})
{{^-last}}