<h3 dir="auto">First Check</h3>
<ul class="contains-task-list">
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I added a very descriptive title to this issue.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I used the GitHub search to find a similar issue and didn't find it.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I searched the FastAPI documentation, with the integrated search.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already searched in Google "How to X in FastAPI" and didn't find any information.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already read and followed all the tutorial in the docs and didn't find an answer.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already checked if it is not related to FastAPI but to <a href="https://github.com/samuelcolvin/pydantic">Pydantic</a>.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already checked if it is not related to FastAPI but to <a href="https://github.com/swagger-api/swagger-ui">Swagger UI</a>.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already checked if it is not related to FastAPI but to <a href="https://github.com/Redocly/redoc">ReDoc</a>.</li>
</ul>
<h3 dir="auto">Commit to Help</h3>
<ul class="contains-task-list">
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I commit to help with one of those options <g-emoji class="g-emoji" alias="point_up_2" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f446.png">👆</g-emoji></li>
</ul>
<h3 dir="auto">Example Code</h3>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

app.add_middleware(SessionMiddleware, secret_key=&quot;test secret key&quot;, https_only=False)
app.add_middleware(HTTPSRedirectMiddleware)


@app.get(&quot;/&quot;)
def read_root():
    return RedirectResponse(&quot;/home&quot;)"><pre class="notranslate"><span class="pl-k">from</span> <span class="pl-s1">fastapi</span> <span class="pl-k">import</span> <span class="pl-v">FastAPI</span>
<span class="pl-k">from</span> <span class="pl-s1">fastapi</span>.<span class="pl-s1">responses</span> <span class="pl-k">import</span> <span class="pl-v">RedirectResponse</span>
<span class="pl-k">from</span> <span class="pl-s1">starlette</span>.<span class="pl-s1">middleware</span>.<span class="pl-s1">sessions</span> <span class="pl-k">import</span> <span class="pl-v">SessionMiddleware</span>
<span class="pl-k">from</span> <span class="pl-s1">fastapi</span>.<span class="pl-s1">middleware</span>.<span class="pl-s1">httpsredirect</span> <span class="pl-k">import</span> <span class="pl-v">HTTPSRedirectMiddleware</span>

<span class="pl-s1">app</span> <span class="pl-c1">=</span> <span class="pl-v">FastAPI</span>()

<span class="pl-s1">app</span>.<span class="pl-en">add_middleware</span>(<span class="pl-v">SessionMiddleware</span>, <span class="pl-s1">secret_key</span><span class="pl-c1">=</span><span class="pl-s">"test secret key"</span>, <span class="pl-s1">https_only</span><span class="pl-c1">=</span><span class="pl-c1">False</span>)
<span class="pl-s1">app</span>.<span class="pl-en">add_middleware</span>(<span class="pl-v">HTTPSRedirectMiddleware</span>)


<span class="pl-en">@<span class="pl-s1">app</span>.<span class="pl-en">get</span>(<span class="pl-s">"/"</span>)</span>
<span class="pl-k">def</span> <span class="pl-en">read_root</span>():
    <span class="pl-k">return</span> <span class="pl-v">RedirectResponse</span>(<span class="pl-s">"/home"</span>)</pre></div>
<h3 dir="auto">Description</h3>
<ul dir="auto">
<li>add breakpoints or print statements in <code class="notranslate">HTTPSRedirectMiddleware.__init__</code></li>
<li>Run the app server. Your breakpoint will hit <code class="notranslate">HTTPSRedirectMiddleware.__init__</code> more than once!</li>
</ul>
<p dir="auto">I'm trying to understand why fastapi/starlette re-initializes middleware IFF the user wants to add more than one middleware, as per my example.</p>
<p dir="auto">I worked on a couple of other ideas to work around this:</p>
<ol dir="auto">
<li>I can see that instead of calling <code class="notranslate">app.add_middleware...</code> I could have also passed in a list of middlewares to the app, like so</li>
</ol>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="from fastapi import FastAPI
from fastapi.middleware import Middleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.sessions import SessionMiddleware

user_middlewares = []
user_middlewares.append(Middleware(HTTPSRedirectMiddleware))

user_middlewares.append(Middleware(SessionMiddleware, secret_key=&quot;test secret key&quot;, https_only=False))

app = FastAPI(middleware=user_middlewares)"><pre class="notranslate"><code class="notranslate">from fastapi import FastAPI
from fastapi.middleware import Middleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.sessions import SessionMiddleware

user_middlewares = []
user_middlewares.append(Middleware(HTTPSRedirectMiddleware))

user_middlewares.append(Middleware(SessionMiddleware, secret_key="test secret key", https_only=False))

app = FastAPI(middleware=user_middlewares)
</code></pre></div>
<p dir="auto">The problem with this approach is that my custom middleware (not shown here as I'm using public ones) needs to have an instance of the FastAPI app passed in. That doesn't work in this case. I make that work in my current implementation by doing it like this</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="app = FastAPI()
app.add_middleware(MyCustomMiddleware, original_app=app)"><pre class="notranslate"><code class="notranslate">app = FastAPI()
app.add_middleware(MyCustomMiddleware, original_app=app)
</code></pre></div>
<p dir="auto">which is my preferred option right now. But as mentioned above, since I'm adding multiple middleware by calling <code class="notranslate">add_middleware</code> twice, I don't want <code class="notranslate">MyCustomMiddleware</code> to be initialized twice!</p>
<p dir="auto">My middleware is defined as follows (redacted for privacy):</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="from starlette.middleware.base import BaseHTTPMiddleware
class MyCustomMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp, original_app: FastAPI = None) -&gt; None:
        self.app = app
        self.original_app = original_app
        self.app_name = self.original_app.title

        self.dispatch_func = self.dispatch_func
       # other critical work that should only happen ONCE ever

    async def dispatch_func(self, request: Request, call_next):
        ....
        # work that relies on calling self.original_app.routes
"><pre class="notranslate"><code class="notranslate">from starlette.middleware.base import BaseHTTPMiddleware
class MyCustomMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp, original_app: FastAPI = None) -&gt; None:
        self.app = app
        self.original_app = original_app
        self.app_name = self.original_app.title

        self.dispatch_func = self.dispatch_func
       # other critical work that should only happen ONCE ever

    async def dispatch_func(self, request: Request, call_next):
        ....
        # work that relies on calling self.original_app.routes

</code></pre></div>
<ol start="2" dir="auto">
<li>I'm also aware that the fastapi way of adding middleware is with the <code class="notranslate">@app.middleware("http")</code> decorator described in the docs <a href="https://fastapi.tiangolo.com/tutorial/middleware/" rel="nofollow">https://fastapi.tiangolo.com/tutorial/middleware/</a>. However, As shown in <code class="notranslate">MyCustomMiddleware</code> implementation, I need it to be class-based for initialization and then for <code class="notranslate">call_next</code> later on</li>
</ol>
<p dir="auto">Is the multiple middleware initialization a design decision or an issue? Is there another way for me to design my CustomMiddleware, be able to add it and any other number of middleware to my app, but without having multiple initialization?</p>
<h3 dir="auto">Operating System</h3>
<p dir="auto">Linux, macOS</p>
<h3 dir="auto">Operating System Details</h3>
<p dir="auto">n/A</p>
<h3 dir="auto">FastAPI Version</h3>
<p dir="auto">0.68.0</p>
<h3 dir="auto">Python Version</h3>
<p dir="auto">3.9</p>
<h3 dir="auto">Additional Context</h3>
<p dir="auto"><em>No response</em></p>
<h3 dir="auto">First Check</h3>
<ul class="contains-task-list">
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I added a very descriptive title to this issue.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I used the GitHub search to find a similar issue and didn't find it.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I searched the FastAPI documentation, with the integrated search.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already searched in Google "How to X in FastAPI" and didn't find any information.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already read and followed all the tutorial in the docs and didn't find an answer.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already checked if it is not related to FastAPI but to <a href="https://github.com/samuelcolvin/pydantic">Pydantic</a>.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already checked if it is not related to FastAPI but to <a href="https://github.com/swagger-api/swagger-ui">Swagger UI</a>.</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I already checked if it is not related to FastAPI but to <a href="https://github.com/Redocly/redoc">ReDoc</a>.</li>
</ul>
<h3 dir="auto">Commit to Help</h3>
<ul class="contains-task-list">
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox" checked=""> I commit to help with one of those options <g-emoji class="g-emoji" alias="point_up_2" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f446.png">👆</g-emoji></li>
</ul>
<h3 dir="auto">Example Code</h3>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="# TIP: This is full app. Run using `uvicorn main:app --port 5000 --reload`

from datetime import datetime
from typing import List

from fastapi import FastAPI
from pydantic import BaseModel

# Fake Data (database)

data = [
    {
        &quot;id&quot;: 1,
        &quot;username&quot;: &quot;johndoe007&quot;,
        &quot;created_at&quot;: datetime.now(),
        &quot;updated_at&quot;: datetime.now(),
    }
]


# Pydantic
class DemoBase(BaseModel):
    username: str


class DemoOut(DemoBase):
    id: int
    created_at: datetime
    updated_at: datetime


# FastAPI
app = FastAPI()


@app.get(&quot;/&quot;, response_model=List[DemoOut])
def read_root():
    return data"><pre class="notranslate"><span class="pl-c"># TIP: This is full app. Run using `uvicorn main:app --port 5000 --reload`</span>

<span class="pl-k">from</span> <span class="pl-s1">datetime</span> <span class="pl-k">import</span> <span class="pl-s1">datetime</span>
<span class="pl-k">from</span> <span class="pl-s1">typing</span> <span class="pl-k">import</span> <span class="pl-v">List</span>

<span class="pl-k">from</span> <span class="pl-s1">fastapi</span> <span class="pl-k">import</span> <span class="pl-v">FastAPI</span>
<span class="pl-k">from</span> <span class="pl-s1">pydantic</span> <span class="pl-k">import</span> <span class="pl-v">BaseModel</span>

<span class="pl-c"># Fake Data (database)</span>

<span class="pl-s1">data</span> <span class="pl-c1">=</span> [
    {
        <span class="pl-s">"id"</span>: <span class="pl-c1">1</span>,
        <span class="pl-s">"username"</span>: <span class="pl-s">"johndoe007"</span>,
        <span class="pl-s">"created_at"</span>: <span class="pl-s1">datetime</span>.<span class="pl-en">now</span>(),
        <span class="pl-s">"updated_at"</span>: <span class="pl-s1">datetime</span>.<span class="pl-en">now</span>(),
    }
]


<span class="pl-c"># Pydantic</span>
<span class="pl-k">class</span> <span class="pl-v">DemoBase</span>(<span class="pl-v">BaseModel</span>):
    <span class="pl-s1">username</span>: <span class="pl-s1">str</span>


<span class="pl-k">class</span> <span class="pl-v">DemoOut</span>(<span class="pl-v">DemoBase</span>):
    <span class="pl-s1">id</span>: <span class="pl-s1">int</span>
    <span class="pl-s1">created_at</span>: <span class="pl-s1">datetime</span>
    <span class="pl-s1">updated_at</span>: <span class="pl-s1">datetime</span>


<span class="pl-c"># FastAPI</span>
<span class="pl-s1">app</span> <span class="pl-c1">=</span> <span class="pl-v">FastAPI</span>()


<span class="pl-en">@<span class="pl-s1">app</span>.<span class="pl-en">get</span>(<span class="pl-s">"/"</span>, <span class="pl-s1">response_model</span><span class="pl-c1">=</span><span class="pl-v">List</span>[<span class="pl-v">DemoOut</span>])</span>
<span class="pl-k">def</span> <span class="pl-en">read_root</span>():
    <span class="pl-k">return</span> <span class="pl-s1">data</span></pre></div>
<h3 dir="auto">Description</h3>
<p dir="auto">If you visit the app you will get below response:</p>
<div class="highlight highlight-source-json notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="[
    {
        &quot;username&quot;: &quot;johndoe007&quot;,
        &quot;id&quot;: 1,
        &quot;created_at&quot;: &quot;2021-09-13T12:57:55.200998&quot;,
        &quot;updated_at&quot;: &quot;2021-09-13T12:57:55.201006&quot;
    }
]"><pre class="notranslate">[
    {
        <span class="pl-ent">"username"</span>: <span class="pl-s"><span class="pl-pds">"</span>johndoe007<span class="pl-pds">"</span></span>,
        <span class="pl-ent">"id"</span>: <span class="pl-c1">1</span>,
        <span class="pl-ent">"created_at"</span>: <span class="pl-s"><span class="pl-pds">"</span>2021-09-13T12:57:55.200998<span class="pl-pds">"</span></span>,
        <span class="pl-ent">"updated_at"</span>: <span class="pl-s"><span class="pl-pds">"</span>2021-09-13T12:57:55.201006<span class="pl-pds">"</span></span>
    }
]</pre></div>
<p dir="auto">It is working fine but the problem is when we want below:</p>
<p dir="auto"><strong>1. order the data sent by <code class="notranslate">response_model</code></strong></p>
<p dir="auto">In the above response, <code class="notranslate">id</code> is returned at 2nd position but I want to return at the 1st position. Requirement for this can be:</p>
<ul dir="auto">
<li>This is how I want my API to respond</li>
<li>As a full stack developer I directly render the response in the table and my <code class="notranslate">id</code> column is placed in 2nd column which should be in 1st row.</li>
</ul>
<p dir="auto"><strong>2. Update the data representation</strong></p>
<p dir="auto">In the above response, we get the date as <code class="notranslate">2021-09-13T12:57:55.200998</code> but I want to return the formatted date which should be human-readable. This is just a single example but there can be others as explained in this <a href="https://github.com/samuelcolvin/pydantic/discussions/3144" data-hovercard-type="discussion" data-hovercard-url="/pydantic/pydantic/discussions/3144/hovercard">discussion</a>.</p>
<h3 dir="auto">Wanted Solution</h3>
<p dir="auto">I guess we can create another magic class that lets us define the field order and value representation but that might introduce code duplication. Sorry but I don't have any perfect solution.</p>
<h3 dir="auto">Wanted Code</h3>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="No idea"><pre class="notranslate"><span class="pl-v">No</span> <span class="pl-s1">idea</span></pre></div>
<h3 dir="auto">Alternatives</h3>
<p dir="auto">None. I might have to raise the same issue to pydantic.</p>
<h3 dir="auto">Operating System</h3>
<p dir="auto">Linux</p>
<h3 dir="auto">Operating System Details</h3>
<p dir="auto">Linux Mint 20.2 Cinnamon</p>
<h3 dir="auto">FastAPI Version</h3>
<p dir="auto">0.68.0</p>
<h3 dir="auto">Python Version</h3>
<p dir="auto">3.9.x</p>
<h3 dir="auto">Additional Context</h3>
<p dir="auto">None</p>