If I understood your question correctly, I suggest you review the following fastapi document.
https://fastapi.tiangolo.com/tutorial/middleware/#before-and-after-the-response