I’m working with a FastAPI project generated by OpenAPI Generator. I want to implement custom logic for my API endpoints, but I’m unsure how to ensure my changes are picked up when running the server.
Project Structure
media_api_python/
└── openapi_server/
├── apis/
│ ├── __init__.py
│ ├── media_files_api.py
│ └── media_files_api_base.py
├── impl/
│ ├── __init__.py
│ └── media_files_api.py
├── main.py
└── models/
├── __init__.py
├── appearance.py
├── bounding_box.py
...
Question
-
How can I implement custom logic in
impl/media_files_api.py
and ensure it’s used when running the server withuvicorn openapi_server.main:app --host 0.0.0.0 --port 8080
? -
Can you provide a simple “Hello World” implementation of the
media_files_mediafile_post
function to demonstrate this approach?
Relevant Code
Here’s the content of media_files_api_base.py
:
class BaseMediaFilesApi:
subclasses: ClassVar[Tuple] = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
BaseMediaFilesApi.subclasses = BaseMediaFilesApi.subclasses + (cls,)
def media_files_mediafile_post(self, file: str) -> object:
...
And here’s the relevant part of media_files_api.py
:
router = APIRouter()
ns_pkg = openapi_server.impl
for _, name, _ in pkgutil.iter_modules(ns_pkg.__path__, ns_pkg.__name__ + "."):
importlib.import_module(name)
@router.post("/MediaFiles/mediafile", ...)
async def media_files_mediafile_post(file: str = Form(None, description="")) -> object:
...
I’d appreciate any guidance on how to properly implement and integrate custom logic in this OpenAPI-generated FastAPI project. Thanks in advance!
In my attempt at solving it, I created this file impl/media_files_api.py
with the following code, with the expectation that it would somehow be picked up and would override the corresponding endpoints in apis/media_files_api.py
, but when I run curl -X POST "http://localhost:8080/MediaFiles/mediafile" -H "Content-Type: application/x-www-form-urlencoded" --data-urlencode "file=$(< setup.cfg)"
, it returns null
, instead of {"Hello": "World: setup.cfg"}
from openapi_server.apis.media_files_api_base import *
class MediaFilesApiImpl(BaseMediaFilesApi):
def media_files_mediafile_post(self, file: str):
print({"Hello": f"World: {file}"}, file)
return {"Hello": f"World: {file}"}